Skip to content

Instantly share code, notes, and snippets.

@folkertdev
Last active January 26, 2017 20:56
Show Gist options
  • Save folkertdev/1cfd9e9769edec030acec99f2d2c3362 to your computer and use it in GitHub Desktop.
Save folkertdev/1cfd9e9769edec030acec99f2d2c3362 to your computer and use it in GitHub Desktop.
Keep track of the number of outstanding http requests
-- Read more about this program in the official Elm guide:
-- https://guide.elm-lang.org/architecture/effects/http.html
module Main exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Http
import Json.Decode as Decode
import Task
main =
Html.program
{ init = init "cats"
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ topic : String
, gifUrl : String
, requests : Int
}
init : String -> ( Model, Cmd Msg )
init topic =
( Model topic "waiting.gif" 0
, getRandomGif topic
)
-- UPDATE
type Msg
= MorePlease
| NewGif (Result Http.Error String)
| HttpRequestWrapper Msg
| IncreaseRequestCounter
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
MorePlease ->
( model, getRandomGif model.topic )
NewGif (Ok newUrl) ->
( { model | topic = model.topic, gifUrl = newUrl }, Cmd.none )
NewGif (Err _) ->
( model, Cmd.none )
HttpRequestWrapper msg ->
let
-- these are the cmds and model that `update (NewGif _) model` returns
( newModel, cmds ) =
update msg model
in
( { newModel | requests = model.requests - 1 }
, cmds
)
IncreaseRequestCounter ->
( { model | requests = model.requests + 1 }
, Cmd.none
)
-- VIEW
view : Model -> Html Msg
view model =
div []
[ h2 [] [ text model.topic ]
, button [ onClick MorePlease ] [ text "More Please!" ]
, br [] []
, img [ src model.gifUrl ] []
, text (toString model.requests)
]
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- HTTP
patchedHttpSend : (Result Http.Error a -> Msg) -> Http.Request a -> Cmd Msg
patchedHttpSend toMsg request =
Cmd.batch
[ Task.perform identity (Task.succeed IncreaseRequestCounter)
, Task.attempt (HttpRequestWrapper << toMsg) (Http.toTask request)
]
getRandomGif : String -> Cmd Msg
getRandomGif topic =
let
url =
"https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=" ++ topic
in
-- Http.send NewGif (Http.get url decodeGifUrl)
patchedHttpSend NewGif (Http.get url decodeGifUrl)
decodeGifUrl : Decode.Decoder String
decodeGifUrl =
Decode.at [ "data", "image_url" ] Decode.string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment