Skip to content

Instantly share code, notes, and snippets.

@TwistingTwists
Forked from Herteby/ID.elm
Created October 4, 2019 09:00
Show Gist options
  • Save TwistingTwists/12c72dbc9c238839d8eab1d5544260d9 to your computer and use it in GitHub Desktop.
Save TwistingTwists/12c72dbc9c238839d8eab1d5544260d9 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