Skip to content

Instantly share code, notes, and snippets.

@rundis
Created March 8, 2016 19:57
Show Gist options
  • Save rundis/23d7ef6ea42842e6f527 to your computer and use it in GitHub Desktop.
Save rundis/23d7ef6ea42842e6f527 to your computer and use it in GitHub Desktop.
elmdecoding
module Posts (..) where
import Comment exposing (..)
import Effects exposing (Effects, Never)
import Html exposing (..)
import Html.Events exposing (..)
import Http
import Json.Decode as Decode exposing (Decoder, (:=))
import List exposing (..)
import Post exposing (..)
import StartApp
import Task
app : StartApp.App PostListContainerModel
app =
StartApp.start
{ init = init
, view = view
, update = update
, inputs = []
}
main : Signal Html
main =
app.html
port tasks : Signal (Task.Task Never ())
port tasks =
app.tasks
type Action
= NoOp
| GetPosts
| ShowPosts (Maybe PostListContainerModel)
type alias PostListContainerModel =
{ posts : List Post.Model }
init : ( PostListContainerModel, Effects Action )
init =
( PostListContainerModel [], Effects.none )
update : Action -> PostListContainerModel -> ( PostListContainerModel, Effects Action )
update action model =
case action of
NoOp ->
( model, Effects.none )
GetPosts ->
( model, getPosts )
ShowPosts maybePosts ->
case maybePosts of
Nothing ->
( model, Effects.none )
Just ps ->
( ps, Effects.none )
view : Signal.Address Action -> PostListContainerModel -> Html
view address model =
div
[]
[ button [ onClick address GetPosts ] [ text "Click to get posts!" ]
, viewPosts model.posts
]
viewPosts : List Post.Model -> Html
viewPosts posts =
ul [] (List.map Post.view posts)
-- This is the key to map the result of the HTTP GET to an Action
-- Note: Task.toMaybe swallows any HTTP or JSON decoding errors
getPosts : Effects Action
getPosts =
Http.get decoderColl "./posts.json"
|> Task.toMaybe
|> Task.map ShowPosts
|> Effects.task
postDecoder : Decoder Post.Model
postDecoder =
Decode.object5
Post.Model
("img" := Decode.string)
("text" := Decode.string)
("source" := Decode.string)
("date" := Decode.string)
("comments" := Decode.list commentDecoder)
commentDecoder : Decoder Comment.Model
commentDecoder =
Decode.object2
Comment.Model
("text" := Decode.string)
("date" := Decode.string)
decoderColl : Decoder PostListContainerModel
decoderColl =
Decode.object1
PostListContainerModel
("posts" := Decode.list postDecoder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment