Created
April 5, 2022 20:25
-
-
Save leomayleomay/4b57e1e78bf07ef18bbbe19c060a88fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fetch_, { RequestInfo, RequestInit, Response } from "node-fetch"; | |
import * as T from "@effect-ts/core/Effect" | |
import { Tagged } from "@effect-ts/core/Case"; | |
export class HttpError extends Tagged("http-error")<{ | |
readonly error: unknown; | |
}> { } | |
export const fetch = (url: RequestInfo, opts?: Omit<RequestInit, "signal">) => | |
T.effectAsyncInterrupt<unknown, HttpError, Response>((cb) => { | |
const { signal, abort } = new AbortController(); | |
fetch_(url, { ...opts, signal }).then( | |
(response) => cb(T.succeed(response)), | |
(error) => cb(T.fail(HttpError.make({ error }))) | |
); | |
return T.succeedWith(() => { | |
abort(); | |
}); | |
}); | |
export class JsonError extends Tagged("json-error")<{ | |
readonly error: unknown; | |
}> { } | |
export const json = (resp: Response) => | |
T.tryCatchPromise( | |
() => resp.json(), | |
(error) => JsonError.make({ error }) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment