Skip to content

map being called for nullable fields #7

@andremw

Description

@andremw

Consider a structure like this:

type internalObj = {name: string}

type obj = {
  id: string,
  internal: option<internalObj>,
}

I already know that the property obj.internal might be missing and I want to decode that to an Option.
I also know that the property internalObj.name can be missing but I want it to always have a default value.

This is how I would write a decoder for the name property with a default value:

let internalObj_decode: Json.Decode.t<internalObj> = {
  open Json.Decode

  map(option(field("name", string)), ~f=name => {
    name: name->Belt.Option.getWithDefault("Default Name"),
  })
}

And this works fine!

But if the decoder for "obj" considers that "internal" is nullable:

let decoder: Json.Decode.t<obj> = {
  open Json.Decode

  map2(field("id", string), field("internal", nullable(internalObj_decode)), ~f=(
    id,
    internal,
  ) => {
    id: id,
    internal: internal,
  })
}

I would expect the decoder for internal to not run if the value is null, like { "id": "123", "internal": null }, but it runs.

Shouldn't nullable prevent running the decoder if the value is null?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions