haskell-servant / servant-elm

Automatically derive Elm functions to query servant webservices
BSD 3-Clause "New" or "Revised" License
164 stars 48 forks source link

Generate BookId instead of (Key Book) for persistent's type aliases #50

Open k-bx opened 5 years ago

k-bx commented 5 years ago

Currently if you have a type alias type BookId = Key Book that you Capture "book-id" BookId it'll be rendered as (Key Book), and you have to replace it manually, like at https://gitlab.com/k-bx/meetup/blob/master/backend/meetup/src/Meetup/GenerateElm.hs. Having a BookId would be nicer.

tkuriyama commented 3 years ago

I've run into this issue as well. Looks like the URL referenced above has moved to https://gitlab.com/k-bx/meetup/-/blob/master/backend/meetup/src/Le/GenerateElm.hs

And the behavior from the persistent side is described for example at https://www.yesodweb.com/book/persistent#persistent_closer_look_at_types

tkuriyama commented 3 years ago

It seems this is already possible by defining something like myAlteration from elm-bridge and then call it from servant-elm's defElmOptions like so:

generateElmModuleWith
    defElmOptions { urlPrefix = Static $ baseURL
                  , elmAlterations = myAlterations }
    [...]
   ... 

... where the alteration looks like:

import           Elm.TyRep as ET
import qualified Elm.Module as Elm

myAlterations :: ET.ETypeDef -> ET.ETypeDef
myAlterations = Elm.recAlterType myTypeAlterations

myTypeAlterations :: ET.EType -> ET.EType
myTypeAlterations t = case t of
  ET.ETyApp (ET.ETyCon (ET.ETCon "Key")) (ET.ETyCon (ET.ETCon "Book")) ->
    ET.ETyCon (ET.ETCon "BookId")
  _ ->
    Elm.defaultTypeAlterations t

But then you still need to specify the type of BookId that matches the database backend, such that elm-bridge can generate the type aliases and serialization functions...