Reputation: 127
I want to wrap Fetch API in fp-ts in some manner:
import * as TE from 'fp-ts/lib/TaskEither';
import * as E from 'fp-ts/lib/Either';
import { flow } from 'fp-ts/lib/function';
import { pipe } from 'fp-ts/lib/pipeable';
const safeGet = (url: string): TE.TaskEither<Error, Response> => TE.tryCatch(
() => fetch(url),
(reason) => new Error(String(reason))
);
const processResponce = flow(
(x: Response): E.Either<Error, Response> => {
return x.status === 200
? E.right(x)
: E.left(Error(x.statusText))
},
TE.fromEither
);
export const httpGet = (url: string): TE.TaskEither<Error, Response> => pipe(
safeGet(url),
TE.chain(processResponce)
);
With this example after running httpGet I get an Response and need to eval .json() method manually. So how can I avoid this behavior and get json inside pipe?
Upvotes: 5
Views: 1839
Reputation: 2201
I'm new to fp-ts, but I wonder if you could leverage the library's json module. There's a parse
and stringify
function in there that returns an Either
. My 2¢:
https://gcanti.github.io/fp-ts/modules/Json.ts.html#parse
Upvotes: 0
Reputation: 437
Just chain this into your flow?
const safeJson = <T = unknown>(resp: Response): TE.TaskEither<Error, T> => TE.tryCatch(
() => resp.json(),
(reason) => new Error(String(reason))
);
Upvotes: 4