Skip to content

Instantly share code, notes, and snippets.

@martimatix
Last active November 23, 2018 08:35
Show Gist options
  • Save martimatix/85e4318497d66c248a0861ed53c62769 to your computer and use it in GitHub Desktop.
Save martimatix/85e4318497d66c248a0861ed53c62769 to your computer and use it in GitHub Desktop.
A beginner's guide to Graphqelm
module Main exposing (main)
import Graphqelm.Operation exposing (RootQuery)
import Graphqelm.Http
import Graphqelm.SelectionSet exposing (SelectionSet, with)
import Html exposing (Html, a, div, h1, h2, p, pre, text)
import RemoteData exposing (RemoteData)
import Github.Object
import Github.Object.User as User
import Github.Query as Query
query : SelectionSet Response RootQuery
query =
Query.selection Response
|> with (Query.user { login = "octocat" } user)
user : SelectionSet User Github.Object.User
user =
User.selection User
|> with User.name
type alias Response =
{ user : Maybe User }
type alias User =
{ name : Maybe String }
-- Get your GitHub bearer access token from https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/
makeRequest : Cmd Msg
makeRequest =
query
|> Graphqelm.Http.queryRequest
"https://api.github.com/graphql"
|> Graphqelm.Http.withHeader "authorization" "Bearer <YOUR GITHUB BEARER TOKEN>"
|> Graphqelm.Http.send (RemoteData.fromResult >> GotResponse)
type Msg
= GotResponse Model
type alias Model =
RemoteData (Graphqelm.Http.Error Response) Response
init : ( Model, Cmd Msg )
init =
( RemoteData.Loading
, makeRequest
)
view : Model -> Html.Html Msg
view model =
div []
[ case model of
RemoteData.Loading ->
text "Loading"
RemoteData.Failure e ->
text <| "Something went wrong: " ++ toString e
RemoteData.NotAsked ->
text "Request has not been made yet"
RemoteData.Success response ->
case response.user of
Just user ->
div []
[ h2 [] [ text (Maybe.withDefault "User has no name" user.name) ] ]
Nothing ->
text "No user was found with that name"
]
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
GotResponse response ->
( response, Cmd.none )
main : Program Never Model Msg
main =
Html.program
{ init = init
, update = update
, subscriptions = \_ -> Sub.none
, view = view
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment