Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save groob/609d758379643e39299b69ee04f6de32 to your computer and use it in GitHub Desktop.
Save groob/609d758379643e39299b69ee04f6de32 to your computer and use it in GitHub Desktop.
Written for Elm Meetup NYC June 9, 2016
import Html.App as Html
import Html exposing (..)
import Html.Events exposing (onInput)
import Html.Attributes exposing (..)
import Json.Decode exposing ((:=), Decoder)
import Json.Encode
import Task
import Http exposing (Error(..))
main =
Html.program
{ init = (initialModel, Cmd.none)
, update = update
, view = view
, subscriptions = (\_ -> Sub.none)
}
type alias Model =
{ input : String
, upperString : String
, count : Int
, error : Maybe String
}
initialModel : Model
initialModel =
{ input = ""
, upperString = ""
, count = 0
, error = Nothing
}
type Msg
= SetInput String
| SetUpper String
| SetCount Int
| SetError Http.Error
| NoOp
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
SetInput str ->
let
url : String
url =
"https://string.groob.io/"
decoderString : Decoder String
decoderString =
("v" := Json.Decode.string)
decoderInt : Decoder Int
decoderInt =
("v" := Json.Decode.int)
body : Http.Body
body =
[ ("s", Json.Encode.string str) ]
|> Json.Encode.object
|> Json.Encode.encode 0
|> Http.string
postUppercase : Task.Task Http.Error String
postUppercase =
Http.post decoderString (url ++ "uppercase") body
postCount : Task.Task Http.Error Int
postCount =
Http.post decoderInt (url ++ "count") body
uppercase : Cmd Msg
uppercase =
Task.perform SetError SetUpper postUppercase
count : Cmd Msg
count =
Task.perform SetError SetCount postCount
in
{ model | input = str } ! [ uppercase, count]
SetUpper str ->
({ model | upperString = str, error = Nothing }, Cmd.none)
SetCount int ->
({ model | count = int, error = Nothing }, Cmd.none)
SetError err ->
({ model | error = Just (httpErrorToString err) }, Cmd.none)
NoOp ->
(model, Cmd.none)
view : Model -> Html Msg
view model =
let
viewError =
case model.error of
Just str ->
div [ class "error" ] [ text str ]
Nothing ->
text ""
in
div
[]
[ input [ onInput SetInput ] []
, div [ class "output" ] [text model.upperString ]
, div [ class "output" ] [text <| toString model.count ]
, viewError
]
httpErrorToString : Http.Error -> String
httpErrorToString error =
case error of
Timeout ->
"Timeout!"
NetworkError ->
"Network Error"
UnexpectedPayload message ->
message
BadResponse status message ->
"status: " ++ (toString status) ++ " " ++ message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment