Given the following data types:
import Json.Decode exposing (Decoder, andThen, map, map2, map4, oneOf, string, succeed, field)
port loginResponse : (Value -> msg) -> Sub msg
type Status
= Authenticated Data
| Unauthenticated (Maybe Error)
type alias Data =
{ accessToken : String
, email : String
, name : String
, nickname : String
}
dataDecoder : Decoder Data
dataDecoder =
map4 Data
(field "accessToken" string)
(field "email" string)
(field "name" string)
(field "nickname" string)
type alias Error =
{ error : String
, errorDescription : String
}
errorDecoder : Decoder Error
errorDecoder =
map2 Error
(field "error" string)
(field "errorDescription" string)
How might I go about writing a decoder to decode Json.Decode.Value types coming out of a Port into the Status custom type?
Closest I can think of is something like:
getStatus : Json.Decode.Value -> Status
getStatus value =
let
decodedData =
decodeValue dataDecoder value
in
case decodedData of
Ok data ->
Authenticated data
Err _ ->
let
decodedError =
decodeValue errorDecoder value
in
case decodedError of
Ok error ->
Unauthenticated (Just error)
Err err ->
Unauthenticated (Just { error = "There was a problem decoding the JSON", errorDescription = "" })
but that doesn’t feel very elegant.