I'm learning fp-ts now and try to replace some parts of my API with its approach.
Simple example:
- get
itemIdwith request - use this
itemIdwith async function to get (or not) the item
The only way I found is:
const itemId: E.Either<string, Item["id"]> = pipe(
body.itemId,
E.fromNullable('Item ID is missed')
);
const item: E.Either<string, Item> = E.isLeft(itemId)
? itemId
: pipe(
await getItem(itemId.right),
E.fromNullable('cant find item')
);
It works. But is it right way? Is it any way to do it all in one pipe function?
Thank you.
There are a few layers to this question so I'll present a possible solution and walk through how it works.
First,
fp-tsusesTasks to represent asynchronous work, so most of the time when working with async code infp-tsyou first convert the code to aTaskorTaskEither(more on that in a second). First, we need a function to perform thegetItemtask and return anEitherinstead ofnullwhen null is returned. This can be defined as:Now we have a function that takes a number and produces a
TaskEitherwhich will fetch the item.Next you want to use this function with your
bodyobject. You can use the newly created function along withbodyto get an item:Finally, you can do something with the value as follows: