Created
March 18, 2020 10:18
-
-
Save kutyel/3867cc5ea3ffeda9ebe272d96ea11f69 to your computer and use it in GitHub Desktop.
Elm 0.19.1 GraphQL Star Wars Example!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main exposing (main) | |
import Browser | |
import GraphQL.Client.Http as GraphQLClient | |
import GraphQL.Request.Builder exposing (..) | |
import Html exposing (Html, div, text) | |
import Task exposing (Task) | |
{-| Responses to `starWarsRequest` are decoded into this type. | |
-} | |
type alias Hero = | |
{ name : String | |
, friends : List String | |
} | |
{-| The definition of `starWarsRequest` builds up a query request value that | |
will later be encoded into the following GraphQL query document: | |
query { | |
hero { | |
name | |
friends { | |
name | |
} | |
} | |
} | |
-} | |
starWarsRequest : Request Query Hero | |
starWarsRequest = | |
let | |
friend = | |
extract (field "name" [] string) | |
hero = | |
object Hero | |
|> with (field "name" [] string) | |
|> with (field "friends" [] (list friend)) | |
queryRoot = | |
extract | |
(field "hero" | |
[] | |
hero | |
) | |
in | |
queryDocument queryRoot |> request {} | |
type alias StarWarsResponse = | |
Result GraphQLClient.Error Hero | |
type alias Model = | |
Maybe StarWarsResponse | |
type Msg | |
= ReceiveQueryResponse StarWarsResponse | |
sendQueryRequest : Request Query a -> Task GraphQLClient.Error a | |
sendQueryRequest request = | |
GraphQLClient.sendQuery "https://elm-graphql.herokuapp.com" request | |
sendStarWarsQuery : Cmd Msg | |
sendStarWarsQuery = | |
sendQueryRequest starWarsRequest | |
|> Task.attempt ReceiveQueryResponse | |
main : Program () Model Msg | |
main = | |
Browser.element | |
{ init = always init | |
, view = view | |
, update = update | |
, subscriptions = subscriptions | |
} | |
init : ( Model, Cmd Msg ) | |
init = | |
( Nothing, sendStarWarsQuery ) | |
view : Model -> Html Msg | |
view model = | |
div [] | |
[ model |> Debug.toString |> text ] | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update (ReceiveQueryResponse response) _ = | |
( Just response, Cmd.none ) | |
subscriptions : Model -> Sub Msg | |
subscriptions _ = | |
Sub.none |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment