【问题标题】:Using TaskEither with fetch API in fp-ts在 fp-ts 中使用 TaskEither 和 fetch API
【发布时间】:2020-06-02 15:43:22
【问题描述】:

我想以某种方式将 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 后,通过这个示例,我得到一个响应,需要手动评估 .json() 方法。那么如何避免这种行为并在管道中获取 json 呢?

【问题讨论】:

  • 你怎么打电话给httpGet?你看到了什么反应?
  • const getActivities = httpGet('fakerestapi.azurewebsites.net/api/Activities/1'); getActivities().then(x => console.log(x));我得到了:{ _tag: 'Right', right: Response { size: 0, timeout: 0, [Symbol(Body internals)]: { body: [Gunzip], distured: false, error: null }, [Symbol(响应内部)]: { url: 'fakerestapi.azurewebsites.net/api/Activities/1', status: 200, statusText: 'OK', headers: [Headers], counter: 0 } } }

标签: typescript fp-ts


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2022-01-07
    • 2022-07-19
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 2021-05-10
    • 2021-12-04
    • 1970-01-01
    相关资源
    最近更新 更多