将TaskEither与fp-ts中的访存API结合使用

时间:2020-06-02 15:43:22

标签: typescript fp-ts

我想以某种方式将Fetch API包装在fp-ts中:

  1. 创建请求
  2. 检查状态
  3. 如果状态正常-返回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之后的此示例中,我得到一个Response,并且需要手动eval .json()方法。那么如何避免这种行为并在管道内获取json?

1 个答案:

答案 0 :(得分:0)

只是将其链接到您的流程中吗?

const safeJson = <T = unknown>(resp: Response): TE.TaskEither<Error, T> => TE.tryCatch(
  () => resp.json(),
  (reason) => new Error(String(reason))
);