Skip to content

Instantly share code, notes, and snippets.

@alg alg/Main.elm
Created Dec 2, 2016

Embed
What would you like to do?
decodeModel : Json.Decode.Value -> Result String Model
decodeModel modelJson =
Json.Decode.decodeValue modelDecoder modelJson
modelDecoder : Json.Decode.Decoder Model
modelDecoder =
Json.Decode.map4 Model
(field "todos" (Json.Decode.list todoDecoder))
(field "todo" todoDecoder)
(field "filter" filterStateDecoder)
(field "nextIdentifier" int)
todoDecoder : Json.Decode.Decoder Todo
todoDecoder =
Json.Decode.map4 Todo
(field "title" Json.Decode.string)
(field "completed" Json.Decode.bool)
(field "editing" Json.Decode.bool)
(field "identifier" Json.Decode.int)
filterStateDecoder : Json.Decode.Decoder FilterState
filterStateDecoder =
let
decodeFilterState string =
case string of
"All" -> Result.Ok All
"Active" -> Result.Ok Active
"Completed" -> Result.Ok Completed
_ -> Result.Err ("Not a valid filterState: " ++ string)
in
customDecoder Json.Decode.string decodeFilterState
customDecoder decoder toResult =
Json.Decode.andThen
(\a ->
case toResult a of
Ok b -> Json.Decode.succeed b
Err err -> Json.Decode.fail err
)
decoder
@gabrielelana

This comment has been minimized.

Copy link

commented Dec 29, 2016

You can rewrite the last part with

filterStrategyDecoder : Decode.Decoder FilterStrategy
filterStrategyDecoder =
    let
        decodeWith : String -> Decode.Decoder FilterStrategy
        decodeWith s =
            case s of
                "All" ->
                    Decode.succeed All

                "Active" ->
                    Decode.succeed Active

                "Completed" ->
                    Decode.succeed Completed

                _ ->
                    Decode.fail (s ++ " is not a valid FilterStrategy")
    in
        Decode.string |> Decode.andThen decodeWith
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.