mdgriffith / elm-codegen

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

Support type and type alias constructors #37

Open tesk9 opened 2 years ago

tesk9 commented 2 years ago

I'd like to be able to use type and type alias constructors from the Gen folder when working with published Elm packages.

For example, if I had:

type Id
    = Id Int

type alias UserFlags =
    { id : Id
    , username : String
    }

I'd like to be able to use a reference to the Id and UserFlags constructors. Something like:

Gen.Json.Decode.map2 Gen.Example.constructors_.userFlags 
    (Gen.Example.constructors_.id (Elm.int 1)) 
    (Elm.string "username123")

that would produce:

Json.Decode.map2 UserFlags (Id 1) "username123"

Right now, I'm doing the equivalent of:

Decode.map2
    (\a b ->
        Elm.apply
            (Elm.value
                { importFrom = [ "Gen.Helper" ]
                , name = "UserFlags"
                , annotation = Nothing
                }
            )
            [ a, b ]
    )
    (Elm.apply
        (Elm.value
            { importFrom = [ "Gen.Helper" ]
            , name = "Id"
            , annotation = Nothing
            }
        )
        [ Elm.int 1 ]
    )
    (Elm.string "username123")
mdgriffith commented 2 years ago

Those exist! But they're probably hard to discover 😅

In the generated file, check out the make_ record. The only difference is that for record type aliases, it doesn't provide the constructor : one -> two -> three -> record form, but the

constructor : { one : Expression, two : Expression, three : Expression} -> Expression 

form.

Could add both if that's useful though

tesk9 commented 2 years ago

Ah! I guess I missed it!

I do think having the constructor : one -> two -> three -> record form in addition would be useful for what I'm trying to do, though, since it can be a bit challenging to switch back and forth from the expression-based api to the inferred type API.