Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested types produce incorrect decoders #66

Closed
arbus opened this issue Mar 22, 2019 · 1 comment
Closed

Nested types produce incorrect decoders #66

arbus opened this issue Mar 22, 2019 · 1 comment
Assignees
Labels
bug Something isn't working

Comments

@arbus
Copy link
Member

arbus commented Mar 22, 2019

given the following Haskell types

data Foo =
    FooOne Text
  | FooTwo Bar
  deriving (Generic)
  deriving (Elm, ToJSON, FromJSON) via ElmStreet Foo

data Bar = Bar
  { barOne :: Int
  , barTwo :: Bool
  }
  deriving (Generic)
  deriving (Elm, ToJSON, FromJSON) via ElmStreet Bar

it encodes and decodes like so:

λ> let x = FooOne "Hello"
λ> encode x
"{\"tag\":\"FooOne\",\"contents\":\"Hello\"}"

λ> let y = FooTwo $ Bar 1 True
λ> encode y
"{\"tag\":\"FooTwo\",\"contents\":{\"two\":true,\"one\":1}}"

The generated elm code for Foo and Bar have the following decoder:

decodeFoo : Decoder Foo
decodeFoo =
    let decide : String -> Decoder Foo
        decide x = case x of
            "FooOne" -> D.field "contents" <| D.map FooOne (D.index 0 D.string)
            "FooTwo" -> D.field "contents" <| D.map FooTwo (D.index 0 decodeBar)
            c -> D.fail <| "Foo doesn't have such constructor: " ++ c
    in D.andThen decide (D.field "tag" D.string)

decodeBar : Decoder Bar
decodeBar = D.succeed Bar
    |> required "one" D.int
    |> required "two" D.bool

The problem is in decide function where it assumes that the values of the contents field will be an array. The generated decoders fail as can be seen here:

> D.decodeString ED.decodeFoo "{\"tag\":\"FooOne\",\"contents\":\"Hello\"}"
Err (Field "contents" (Failure ("Expecting an ARRAY") <internals>))
    : Result D.Error ElmStreet.Types.Foo
> D.decodeString ED.decodeFoo "{\"tag\":\"FooTwo\",\"contents\":{\"two\":true,\"one\":1}}"
Err (Field "contents" (Failure ("Expecting an ARRAY") <internals>))
    : Result D.Error ElmStreet.Types.Foo
@arbus arbus added the bug Something isn't working label Mar 22, 2019
@chshersh chshersh self-assigned this Mar 25, 2019
@chshersh
Copy link
Contributor

I'm looking into this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants