Skip to content

Instantly share code, notes, and snippets.

@lenards
Forked from Herteby/ID.elm
Created November 21, 2019 22:24
Show Gist options
  • Save lenards/1ea4451206203ce212c86653aef9b30c to your computer and use it in GitHub Desktop.
Save lenards/1ea4451206203ce212c86653aef9b30c 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 )
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment