我想以某种方式将Fetch API包装在fp-ts中:
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)
);
在运行httpGet之后的此示例中,我得到一个Response,并且需要手动eval .json()方法。那么如何避免这种行为并在管道内获取json?
答案 0 :(得分:0)
只是将其链接到您的流程中吗?
const safeJson = <T = unknown>(resp: Response): TE.TaskEither<Error, T> => TE.tryCatch(
() => resp.json(),
(reason) => new Error(String(reason))
);