Skip to content

Instantly share code, notes, and snippets.

@martimatix
Last active August 2, 2018 21:46
Show Gist options
  • Save martimatix/ee28cb20e2dd514bccf9f43a18ec060d to your computer and use it in GitHub Desktop.
Save martimatix/ee28cb20e2dd514bccf9f43a18ec060d to your computer and use it in GitHub Desktop.
Optional arguments with 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, img)
import Html.Attributes exposing (src)
import RemoteData exposing (RemoteData)
import Github.Object
import Github.Object.User as User
import Github.Query as Query
import Github.Scalar
import Graphqelm.OptionalArgument exposing (OptionalArgument(Present))
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
|> with
(User.avatarUrl
(\optionals -> { optionals | size = Present 200 })
)
type alias Response =
{ user : Maybe User }
type alias User =
{ name : Maybe String
, avatarUrl : Github.Scalar.Uri
}
makeRequest : Cmd Msg
makeRequest =
query
|> Graphqelm.Http.queryRequest
"https://api.github.com/graphql"
|> Graphqelm.Http.withHeader "authorization" "Bearer <replace with your Github access 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) ]
, profilePicture user.avatarUrl
]
Nothing ->
text "No user was found with that name"
]
profilePicture : Github.Scalar.Uri -> Html.Html Msg
profilePicture (Github.Scalar.Uri imageUrl) =
img [ src imageUrl ] []
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