Skip to content

Instantly share code, notes, and snippets.

@alg
Created December 2, 2016 10:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alg/9b47b40ecc7f7e06cac252bf764db4d2 to your computer and use it in GitHub Desktop.
Save alg/9b47b40ecc7f7e06cac252bf764db4d2 to your computer and use it in GitHub Desktop.
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
Copy link

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