Last active
June 13, 2023 23:22
-
-
Save nireno/c4c0c68c2c68807447bf86e2b8edf3be to your computer and use it in GitHub Desktop.
Decoding optional and default values with decco ppx in rescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module RequiredField = { | |
@decco | |
type t = {value: string} | |
} | |
module RequiredFieldWithDefault = { | |
@decco | |
type t = { | |
@decco.default("fallback") | |
value: string, | |
} | |
} | |
module OmittableOrNullableField = { | |
@decco | |
type t = {value: option<string>} | |
} | |
module OmittableOrNullableFieldWithDefault = { | |
@decco | |
type t = { | |
@decco.default(Some("fallback")) | |
value: option<string>, | |
} | |
} | |
let fieldOmitted = %raw(`{}`) | |
let fieldPresentButNull = %raw(`{"value": null}`) | |
let fieldPresentButUndefined = %raw(`{"value": undefined}`) | |
let fieldPresent = %raw(`{"value": "present"}`) | |
Js.log(( | |
"RequiredField", | |
RequiredField.t_decode(fieldOmitted), // Error: value not a string | |
RequiredField.t_decode(fieldPresentButNull), // Error: value not a string | |
RequiredField.t_decode(fieldPresentButUndefined), // Error: value not a string (undefined is not a valid JSON value) | |
RequiredField.t_decode(fieldPresent), // Ok {value: "present"} | |
)) | |
Js.log(( | |
"RequiredFieldWithDefault", | |
RequiredFieldWithDefault.t_decode(fieldOmitted), // Ok {value: "fallback"} | |
RequiredFieldWithDefault.t_decode(fieldPresentButNull), // Error: value not a string (Was hoping for Ok {value: "fallback"} here) | |
RequiredFieldWithDefault.t_decode(fieldPresentButUndefined), // Error: value not a string | |
RequiredFieldWithDefault.t_decode(fieldPresent), // Ok {value: "present"} | |
)) | |
Js.log(( | |
"OmittableOrNullableField", | |
OmittableOrNullableField.t_decode(fieldOmitted), // Ok {value: None} | |
OmittableOrNullableField.t_decode(fieldPresentButNull), // Ok {value: None} | |
OmittableOrNullableField.t_decode(fieldPresentButUndefined), // Error: value not a string | |
OmittableOrNullableField.t_decode(fieldPresent), // Ok {value: Some("present")} | |
)) | |
Js.log(( | |
"OmittableOrNullableFieldWithDefault", | |
OmittableOrNullableFieldWithDefault.t_decode(fieldOmitted), // Ok {value: None} | |
OmittableOrNullableFieldWithDefault.t_decode(fieldPresentButNull), // Ok {value: None} | |
// (Note that falling back to None makes this no better than the OmittableOrNullableField case) | |
OmittableOrNullableFieldWithDefault.t_decode(fieldPresentButUndefined), // Error: value not a string | |
OmittableOrNullableFieldWithDefault.t_decode(fieldPresent), // Ok {value: Some("present")} | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment