Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for customizing encoded variant values. #36

Open
mrmurphy opened this issue Dec 5, 2019 · 3 comments
Open

Support for customizing encoded variant values. #36

mrmurphy opened this issue Dec 5, 2019 · 3 comments

Comments

@mrmurphy
Copy link
Contributor

mrmurphy commented Dec 5, 2019

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
Copy link
Member

ryb73 commented Dec 6, 2019

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.

@mrmurphy
Copy link
Contributor Author

mrmurphy commented Dec 6, 2019 via email

@danwetherald
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants