I just want to tell people about my experience using the
elm-codec package made by miniBill:
This package was recently highlighted in Elm Weekly so I decided to give it a spin. The selling point was simultaneously defining both the encoder and decoder, which is convenient, and after enjoying using for some simple stuff, I decided to try and use it to write the encoders/decoders for some recursive types, which I’ve been dreading. The data type looks like this:
type Requirement a = Data a | Not (Requirement a) | Or (Requirement a) (Requirement a) | And (Requirement a) (Requirement a) | Any (List (Requirement a)) | All (List (Requirement a))
elm-codec has some tools for dealing with this type of data structure. The codec, which you use to create the encoder and decoder, is made using the
Codec.custom functions. Here’s the code for my codec:
requirementCodec : Codec a -> Codec (Requirement a) requirementCodec meta = Codec.recursive (\rmeta -> Codec.custom (\fdata fnot for fand fany fall value -> case value of Data data -> fdata data Not requirement -> fnot requirement Or requirement1 requirement2 -> for requirement1 requirement2 And requirement1 requirement2 -> fand requirement1 requirement2 Any requirements -> fany requirements All requirements -> fall requirements ) |> Codec.variant1 "Data" Data meta |> Codec.variant1 "Not" Not rmeta |> Codec.variant2 "Or" Or rmeta rmeta |> Codec.variant2 "And" And rmeta rmeta |> Codec.variant1 "Any" Any (Codec.list rmeta) |> Codec.variant1 "All" All (Codec.list rmeta) |> Codec.buildCustom )
It was really quick to get this up and running, the compiler (as always) held my hand. The JSON that it produces is sensible and easy to work with on the back end.
I don’t know the author or anything, just wanted to highlight a very positive experience that I had using a module!