Skip to content

Instantly share code, notes, and snippets.

@dteoh
Last active April 2, 2019 01:31
Show Gist options
  • Save dteoh/ba82f8623893a3c1e0f489d89278c7ff to your computer and use it in GitHub Desktop.
Save dteoh/ba82f8623893a3c1e0f489d89278c7ff to your computer and use it in GitHub Desktop.
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