ahultgren / swagger-elm

Generate Elm types and decoders based on a Swagger file
74 stars 9 forks source link

Null objects defined without properties are not Nothing #20

Open ahultgren opened 7 years ago

ahultgren commented 7 years ago

Consider the code


type alias ArticleRecord =
    { rules : Maybe Rules
    -- other non-pertinent stuff
    }

decodeArticle : Decoder ArticleRecord
decodeArticle =
    decode ArticleRecord
        |> maybe "rules" decodeRules

type alias RulesRecord =
    {}

decodeRules : Decoder RulesRecord
decodeRules =
    decode RulesRecord

and the json:

{
  "rules": null
}

and:

{}

They should be both decoded into:

{ rules = Nothing
}

but the first one (with null) is decode into:

{ rules: Just {}
}

It seems the culprit is Json.Decode.Pipeline.optional. As the docs says:

If valDecoder fails on a null value, then the fallback is used as if the field were missing entirely.

So that makes sense, since an empty record apparently doesn't fail on null. But from reading the code it seems Json.Decode.oneOf [ Json.Decode.null fallback, decoder ] should decode null to fallback.

Anyway it needs a solution.