rescript-labs/decco

Support for customizing encoded variant values.

mrmurphy opened this issue · 3 comments

I'd really love the ability to customize the string representation of non-polymorphic variants. Maybe something like this?

[@decco]
type purchaseType =
  | [@decco.as "premium_subscription"] PremiumSubscription
  | [@decco.as "plus_purchases"] PlusPurchase
  | [@decco.as "gift"] Gift;

My current approach is to write a custom decoder in a new module for that specific type, doing the stringification and parsing by hand. That's fine, and it works, but it's a bit labor-intensive, so I find myself opting to use strings instead of variants in my code, just because I don't want to write codecs for them.

(may be related to #3)

I guess the challenge would be, what would the PPX do if I tried to use this decorator on a variant that contains data? Could we make a sensible compiler error for that?

ryb73 commented

Yep, this is roughly the problem I was going for in #3.

My approach to this so far has been the same as yours from the sound of it (custom decoders) and I agree that it seems labor-intensive for something that it seems could be automated.

I think we could definitely do this, maybe by disallowing [@decco.as] for any variant constructor that doesn't have [edit: I think I meant has?] parameters? The idea is that [@decco.as] could be added to any (not necessarily all) constructors on a type. If a constructor has [@decco.as] it would encode to (for encoders) or look for (for decoders) that value, and otherwise the variant would be treated as normal.

Is there an easy way to skip the array on encode?

@decco
type order = {
  name: string,
}

@decco
type rule =
  | Order(order)

Now:

//rule_encode
["Order", {name: "John Smith"}]

Request:

//rule_encode
{name: "John Smith"}

Not exactly sure how to accomplish this with a custom codec or if that is the best way to achieve this.