Null handling?
suzdalnitski opened this issue · 4 comments
Hi,
It seems that null values in Json can't be parsed. Eg the following fails:
`
{
"errors": [
{
"extensions": {
"code": "unauthenticated",
"reference": null
},
"message": "You must be authenticated to perform this action",
"path": [ "startPlanCheckout" ]
}
]
}
`
->Js.Json.parseExn
->JsonCombinators.Json.decode(DecodeErrors.fetchResult)My decoder is:
module DecodeErrors = {
open JsonCombinators.Json.Decode
type extensions = {
code: string,
reference: option<string>,
}
type error = {
message: string,
path: array<string>,
extensions: extensions,
}
type fetchResult = {errors: option<array<error>>}
let errorField = object(field => {
message: field.required(. "message", string),
path: field.required(. "path", array(string)),
extensions: field.required(.
"extensions",
object(field => {
code: field.required(. "code", string),
reference: field.optional(. "reference", string),
}),
),
})
let fetchResult = object(field => {
errors: field.optional(. "errors", array(errorField)),
})
}This results in the following error: Expected string, got null\n\tat field 'reference'\n\ta…tensions'\n\tin array at index 0\n\tat field 'errors'
It seems that optional doesnt support nulls (which makes sense since Noneis compiled toundefined` in Rescript).
Is there a way to make nulls also be treated as optional?
Thanks!
That's what option is for. Try:
reference: field.required(. "reference", option(string)),
If optional also accepted null you wouldn't be able to distinguish between the field being null and not being present at all.
Yup, this works for null!
However, this fails with undefined values (as expected).
Is there a way to make this work with both null and undefined? Something similar to Js.Nullable.t? I don't think I ever had a use case, where I had to distinguish between the two.
Thanks!
This should work:
reference: field.optional(. "reference", option(string))->Belt.Option.flatMap(x => x),
Eventually you'll be able to use Option.flat from rescript-core.
That makes sense, thank you!