TaskEither and io-ts

In this page we will learn how to fetch data from an endpoint and validate (check) that the data returned is what we expect. To do this we will use the io-ts library that uses an Either for representing the or the correct value or the errors in the validation.

In this case the program is made up by two operations, fetch the data and validate returned data. Let's start by focusing on the fetch

import { pipe } from "fp-ts/lib/pipeable";
import * as E from "fp-ts/lib/Either";
import * as TE from "fp-ts/lib/TaskEither";

function getStuff(u: string): TE.TaskEither<Error, unknown> {
  return TE.tryCatch(
    () =>
      fetch(u).then(res => {
        if (!res.ok) {
          throw new Error(`fetch failed with status: ${res.status}`);
        }
        return res.json();
      }),
    E.toError
  );
}

First of all since a Promise is not referentially transparent we use tryCatch to make it, if you already have a fetch wrapped in an utility you can use that instead.

Now lets implement a io-tsarrow-up-right codec for a Studio Ghibli Filmarrow-up-right

Now we can pipe those two together.

circle-info

Note that in order to work we need to lift an Either to a TaskEither using a function.

Now lets extract the values using fold and transforming it in a string that will be printed

circle-info

Note that fold "exits" the Either but not from the Task

circle-info

You can find a more complete implementation herearrow-up-rightin the file example.ts

Last updated