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";functiongetStuff(u:string):TE.TaskEither<Error,unknown> {returnTE.tryCatch( () =>fetch(u).then(res => {if (!res.ok) {thrownewError(`fetch failed with status: ${res.status}`); }returnres.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 extract the values using fold and transforming it in a string that will be printed
Note that fold "exits" the Either but not from the Task
import*as T from"fp-ts/lib/Task";constTaskEitherAndValidate=pipe(getStuff("https://ghibliapi.herokuapp.com/films/58611129-2dbc-4a81-a72f-77ddfc1b1b49" ),TE.chain(res =>decode(res)),TE.fold( e =>T.of(`oh no, an error occurred: ${e.message}`), film =>T.of(`Film recovered succesfully, title is: ${film.title}`) ));TaskEitherAndValidate().then(msg => {console.log(msg);// "Film recovered succesfully, title is: My Neighbor Totoro"});
You can find a more complete implementation herein the file example.ts