Arseniy Prosvirnin
Arseniy Prosvirnin

Reputation: 127

Using TaskEither with fetch API in fp-ts

I want to wrap Fetch API in fp-ts in some manner:

  1. create request
  2. check status
  3. if status is ok - return 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. So how can I avoid this behavior and get json inside pipe?

Upvotes: 5

Views: 1839

Answers (2)

John Gordon
John Gordon

Reputation: 2201

I'm new to fp-ts, but I wonder if you could leverage the library's json module. There's a parse and stringify function in there that returns an Either. My 2¢:

https://gcanti.github.io/fp-ts/modules/Json.ts.html#parse

Upvotes: 0

Alfred Young
Alfred Young

Reputation: 437

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

Upvotes: 4

Related Questions