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

Using the appropriate toString functions for different types #59

Closed szg251 closed 4 years ago

szg251 commented 4 years ago

Problem

If a query param is other than Int or String (like Bool, Float or some custom type), the String.fromInt will cause a type error on the Elm side. This is due to the change in Elm 0.19, replacing the polymorphic toString function with several monomorphic ones.

Solution

Type checking on code generation, inserting the appropriate function. To support custom types, I added this function as an option to ElmOptions. This way we can use other types like Time.Posix:

customTypeAlterations :: EType -> EType
customTypeAlterations t =
  case t of
    ETyCon (ETCon "PosixTime") -> ETyCon (ETCon "Posix")
    _ -> t

customToString :: EType -> Text
customToString t =
  case t of
    (ETyCon (ETCon "PosixTime")) -> "(Time.posixToMillis >> String.fromInt)"
    _ -> defaultElmToString t

Problems:

I removed the maybeBoolToIntStr function with the new polymorphic one, but if I use the same approach in query params, using "1" as True and "0" as False, I get a parse error on the server side. So I used "true" and "false" instead, but I am not sure, if it would break the original implementation.

k-bx commented 4 years ago

Fantastic work, thank you! Released under 0.7.0

szg251 commented 4 years ago

Thank you!