Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A pattern for encoding records with bs-json

A pattern for encoding records with bs-json

If you have a record type like:

type post = {
  title: string,
  body: string,
};

... you can encode it into a Js.Json.t with the bs-json library like so:

let encode: post => Js.Json.t = obj => {
  Json.Encode.(
    object_([
      ("title", string(obj.title)),
      ("body", string(obj.body)),
    ])
  );
};

... and sometime down the road, you add an extra field:

type post = {
  title: string,
  body: string,
  author: string,
};

... it would be great if the compiler tells you that the encode function is not handling the new author field.

What you can do is to use a combination of record destructuring and compiler errors to make this possible.

Setup

In bsconfig.json add or update the following:

{
  ...
  "warnings": {
    "number": "+9",
    "error": "+101+9+27"
  },
  ...
}

The numbers 9 and 27 are described in OCaml's compiler options page. Basically, 9 will inform you of incomplete record destructuring and 27 will inform you of unused variables.

The pattern

With the setup complete the encode function can be updated to:

let encode: post => Js.Json.t = obj => {
  let {title, body} = obj;
  Json.Encode.(
    object_([
      ("title", string(title)),
      ("body", string(body)),
    ])
  );
};

If you add an extra field to the record type, the compiler will now give you an error, because you forgot to add the new field to the variable list.

If you add the new variable but forget to use the variable, the compiler will now give you an error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.