mdgriffith / elm-codegen

https://package.elm-lang.org/packages/mdgriffith/elm-codegen/latest/
BSD 3-Clause "New" or "Revised" License
137 stars 16 forks source link

Example for JSON decoders #58

Open MattiaVerticchio opened 1 year ago

MattiaVerticchio commented 1 year ago

Hi, and thanks for making elm-codegen! 😁

If I understood correctly, one of its goals is boilerplate or repetitive code generation, such as JSON codecs or encoders-decoders. However, It isn’t clear how to use regular Elm types to generate an encoder or decoder, and it would be really helpful to have this common use case in the docs.

Is it possible to add an example to the README.md?

simonh1000 commented 10 months ago

Seconded I've been trying a couple of hours and got to

renderFile =
    let
        anonFn : Expression -> Expression
        anonFn _ =
            Elm.fn ( "name", Nothing )
                (\firstArgument -> Elm.record [ ( "name", firstArgument ) ])

        setter =
            Elm.Declare.value "decodeHighlight"
                (Gen.Json.Decode.map anonFn Gen.Json.Decode.string)
    in
    Elm.file [ "MyFile" ]
        [ setter.declaration
        ]

but that generates

decodeHighlight : Json.Decode.Decoder (name -> { name : name })
decodeHighlight =
    Json.Decode.map (\mapUnpack -> \name -> { name = name }) Json.Decode.string

which is \mapUnpack -> too much