简体   繁体   English

在 fp-ts 中使用 TaskEither 和 fetch API

[英]Using TaskEither with fetch API in fp-ts

I want to wrap Fetch API in fp-ts in some manner:我想以某种方式将 Fetch API 包装在 fp-ts 中:

  1. create request创建请求
  2. check status检查状态
  3. if status is ok - return json如果状态正常 - 返回 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)
);

With this example after running httpGet I get an Response and need to eval.json() method manually.在运行 httpGet 后使用此示例,我得到一个响应并需要手动 eval.json() 方法。 So how can I avoid this behavior and get json inside pipe?那么如何避免这种行为并在 pipe 中获取 json?

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))
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM