Library to use GraphQL API easily.
Example to configure the API with a token in the authorization header:
config : String -> GraphQL.Config config token = GraphQL.Config [ ("authorization", token) ] "/api/graphql"
Example to create a request:
getUsers : String -> (GraphQL.Purpose Users -> msg) -> Cmd msg getUsers token resultCallback = GraphQL.cmd (myRequest token) resultCallback
myRequest : String -> Http.Request (GraphQL.Response Users) myRequest token = GraphQL.exec (config token) "users" |> GraphQL.query myQuery |> GraphQL.variabes Encode.null |> GraphQL.decoder User.usersDecoder
myQuery : String myQuery = """ query { users { id login firstname lastname email } } """
Example to get the results:
type Msg = GetUsers -- msg to execute the request | OnGetUsers (GraphQL.Purpose Users) -- msg to receive the data ...
update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of GetUsers -> getUsers "myToken" OnGetUsers OnGetUsers res -> GraphQL.response model res (\users -> { model | ... } ! [ ... ] ) -- if success (\error -> { model | ... } ! [ ... ] ) -- if error
Full API response.
There are two types of errors with the GraphQL:
Response type)Purpose is an abstraction for these 2 types of errors.
GraphQL response:
{
data: { <query>: <result>|null },
errors: [
{ message: ... }, ...
]
}If there is a GraphQL error:
data property is nullerrors array is not empty.Create a GraphQL request.
Example:
myRequest : String -> Http.Request (GraphQL.Response Users) myRequest token = GraphQL.exec (config token) "users" |> GraphQL.query myQuery |> GraphQL.variabes Encode.null |> GraphQL.decoder User.usersDecoder
Helper to set the query for the GraphQL request in exec.
Create a Cmd with the GraphQL request create with exec.
Example
getUsers : String -> (GraphQL.Purpose Users -> msg) -> Cmd msg getUsers token resultCallback = GraphQL.cmd (myRequest token) resultCallback
Helper to set the query variables for the GraphQL request in exec.
Helper to set the JSON decoder for the GraphQL request response in exec.
Helper to parse the GraphQL response.
Example: update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of ... OnGetUsers res -> GraphQL.response model res (\users -> { model | users = users, success = Just "get all users" } ! [] ) (\error -> { model | error = Just error } ! [] )
Configure the headers and the url to use the GraphQL API.
Example for an API with JWT token:
config : String -> GraphQL.Config config token = GraphQL.Config [ ("authorization", "Bearer " ++ token) ] "/api/graphql"