我想以某种方式将 Fetch API 包装在 fp-ts 中:
- 创建请求
- 检查状态
- 如果状态正常 - 返回 json
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 后使用此示例,我得到一个响应并需要手动评估 .json() 方法。那么如何避免这种行为并在管道中获取 json 呢?