Created
October 4, 2019 07:21
-
-
Save Herteby/e3f23118a64027c4cca6ca308f76b172 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Thank you for this 🙇♂️