Skip to content

Instantly share code, notes, and snippets.

@Herteby
Created October 4, 2019 07:21
Show Gist options
  • Save Herteby/e3f23118a64027c4cca6ca308f76b172 to your computer and use it in GitHub Desktop.
Save Herteby/e3f23118a64027c4cca6ca308f76b172 to your computer and use it in GitHub Desktop.
module ID exposing (ID(..), decodeFromString, decoder, encode, encodeAsString, fromInt, toInt, toString)
import Json.Decode as Decode exposing (Decoder)
import Json.Encode as Encode exposing (Value)
{-| This type ensures you get a type error if you for example accidentally pass a UserId in place of a CompanyId
-}
type ID phantom
= ID Int
toInt : ID phantom -> Int
toInt (ID int) =
int
fromInt : Int -> ID phantom
fromInt int =
ID int
toString : ID phantom -> String
toString (ID int) =
String.fromInt int
decoder : Decoder (ID phantom)
decoder =
Decode.map ID Decode.int
encode : ID phantom -> Value
encode (ID int) =
Encode.int int
encodeAsString : ID phantom -> Value
encodeAsString (ID int) =
Encode.string (String.fromInt int)
decodeFromString : Decoder (ID phantom)
decodeFromString =
Decode.string
|> Decode.andThen
(\string ->
case String.toInt string of
Just int ->
Decode.succeed int
Nothing ->
Decode.fail ("ID is not convertible to Int: " ++ string)
)
|> Decode.map ID
module User exposing (ID, User, UserId(..), decoder, encode)
import ID
import Json.Decode as Decode exposing (Decoder)
import Json.Encode as Encode exposing (Value)
type UserId
= UserId
type alias ID =
ID.ID UserId
type alias User =
{ id : ID
, name : String
}
decoder : Decoder User
decoder =
Decode.map2 User
(Decode.field "id" ID.decoder)
(Decode.field "name" Decode.string)
encode : User -> Value
encode user =
Encode.object
[ ( "id", ID.encode user.id )
, ( "name", Encode.string user.name )
]
@lenards
Copy link

lenards commented Oct 4, 2019

Thank you for this 🙇‍♂️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment