Last active
June 10, 2016 16:58
-
-
Save strickinato/4c6c1815bfcdf32e38f582d028120edd to your computer and use it in GitHub Desktop.
Written for Elm Meetup NYC June 9, 2016
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
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 | |
, error : Maybe String | |
} | |
initialModel : Model | |
initialModel = | |
{ input = "" | |
, upperString = "" | |
, error = Nothing | |
} | |
type Msg | |
= SetInput String | |
| SetUpper String | |
| SetError Http.Error | |
| NoOp | |
update : Msg -> Model -> (Model, Cmd Msg) | |
update msg model = | |
case msg of | |
SetInput str -> | |
let | |
url : String | |
url = | |
"http://localhost:9999/upper" | |
decoder : Decoder String | |
decoder = | |
("output" := Json.Decode.string) | |
body : Http.Body | |
body = | |
[ ("text", Json.Encode.string str) ] | |
|> Json.Encode.object | |
|> Json.Encode.encode 0 | |
|> Http.string | |
httpPostAsTask : Task.Task Http.Error String | |
httpPostAsTask = | |
Http.post decoder url body | |
command : Cmd Msg | |
command = | |
Task.perform SetError SetUpper httpPostAsTask | |
in | |
({ model | input = str }, command) | |
SetUpper str -> | |
({ model | upperString = str, 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 ] | |
, 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
I updated it in my fork to do both
count
anduppercase
. Gave me a chance to use! [ ]
to batch commands.