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

Parse variant or polymorphic variant #76

Closed
mununki opened this issue Jul 12, 2021 · 3 comments
Closed

Parse variant or polymorphic variant #76

mununki opened this issue Jul 12, 2021 · 3 comments

Comments

@mununki
Copy link

mununki commented Jul 12, 2021

I realized that parsing the variant or polymorphic variant doesn't work with just a string that is the same as the variant or polymorphic variant. I found that the JSON value should be an array type. For example,

// Not working
let responseJson1 = `{
  "status": "SUCCESS"
}`

// Working
let responseJson2 = `{
  "status": [ "SUCCESS" ]
}`

@decco
type staus = SUCCESS | FAIL

@decco
type response = {
  status,
  ...
}

I think it is reasonable in a way. But, parsing "SUCCESS" into variant or polymorphic variant would be also reasonable. Is there any workaround to parse it in this way or any plan?

@ryb73
Copy link
Member

ryb73 commented Jul 12, 2021

Hi @mattdamon108 – please see #36

As for a workaround, you can use [@decco.codec] or manually override the *type*_encode and *type*_decode functions.

@ryb73 ryb73 closed this as completed Jul 12, 2021
@mununki
Copy link
Author

mununki commented Jul 13, 2021

Working lovely! Thanks!

@decco
type orderStatus = PROCESSING | SUCCESS | FAIL

@decco
type order = {
  @decco.key("order-status") orderStatus: @decco.codec(Decco.Codecs.magic) orderStatus,
}

@mununki
Copy link
Author

mununki commented Jul 13, 2021

I found that the above my workaround is parsing it to a string, not a variant. Therefore, I had to make a custom encoder and decoder to parse as a result.

type orderStatus = PROCESSING | SUCCESS | FAIL

let encoderOrderStatus = v =>
  switch v {
  | PROCESSING => "CREATE"
  | SUCCESS => "STANDBY"
  | FAIL => "DELIVERING"
  }->Js.Json.string

let decoderOrderStatus = json => {
  switch json |> Js.Json.classify {
  | Js.Json.JSONString(str) =>
    switch str {
    | "PROCESSING" => PROCESSING->Ok
    | "SUCCESS" => SUCCESS->Ok
    | "FAIL" => FAIL->Ok
    | _ => Error({Decco.path: "", message: "Expected JSONString", value: json})
    }
  | _ => Error({Decco.path: "", message: "Expected JSONString", value: json})
  }
}

let codecOrderStatus: Decco.codec<orderStatus> = (encoderOrderStatus, decoderOrderStatus)

@decco
type order = {
  @decco.key("order-status") orderStatus: @decco.codec(codecOrderStatus) orderStatus,,
}

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

2 participants