How to create a custom variant codec in elm-serializer?

I am using custom types for routing to different pages in my web app. I like using custom types for page routing because the compiler checks ensure that all routes to all pages work.

I am using Browser.application and I also handle onUrlChange requests. So, I need to translate url fragments (a string) to my custom type again. That is simple enough. Just create a bunch of if…then statements mapping strings to the custom type variants.

However, if I add a variant to my custom type and forget to add another if…then statement in url -> custom type translate function my web app contains a bug. The compiler does not catch this.

So, I thought of using a Codec using elm-serializer. And this works. I have compiler checks and encoding en decoding are nicely linked to each other.

However, my url now contains meaningless translations of variants. For example: the variant Apple is translated to AQAA and I don’t like AQAA in the url’s of my web app. I would like to have the variant Apple translated to ‘apple’.

I know elm-serialize says in the README: not good for “Encoding to a human readable format”.

Still, my question is: can I use a custom variant encoder/decoder in elm-serialize? Or is there another way to closely link the encoding and decoding of a custom type?

I have created a simple Ellie app that uses a custom Codec for a custom type. See: https://ellie-app.com/bT6w5QwwbP6a1

I think this might be a better fit for a package @miniBill is working on that lets you create codecs specifically designed to handle routing. It’s not officially released but there might be a usable version of it available somewhere.

Looking for code by @miniBill I found this discussion from last September that basically discusses the same question. @miniBill created some interesting code in Ellie. I have take a good look at it. But by the looks of it, it would indeed be great if this becomes available in a library. See: https://discourse.elm-lang.org/t/extracting-type-metadata-from-elm-code/6251

I’ve published some updated code at https://github.com/miniBill/elm-url-codec

The main problems are:

  1. the Advanced module types are very complex (the API is nice, the types… not);
  2. the “Basic” module doesn’t typecheck yet (I still haven’t figured it out).

If I can fix at least the second one I can consider publishing it. Otherwise… feel free to use the code under BSD-3.

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.