servant-elm icon indicating copy to clipboard operation
servant-elm copied to clipboard

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

Open k-bx opened this issue 6 years ago • 2 comments

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.

k-bx avatar May 28 '19 13:05 k-bx

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 avatar Nov 11 '20 17:11 tkuriyama

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...

tkuriyama avatar Nov 11 '20 21:11 tkuriyama