import { Effect, pipe } from "effect";
class FetchError extends Error {
readonly _tag = "FetchError";
}
class HttpError extends Error {
readonly _tag = "HttpError";
}
const getUrl = (input: RequestInfo) =>
typeof input === "string" ? input : input.url;
const fetchEffect = Effect.tryPromise({
try: () => fetch(input, init),
catch: e =>
new FetchError(
`Failed to fetch url: ${getUrl(input)} with error: ${
e instanceof Error && e.message
}`
)
});
const handleHttpError = (response: Response) => {
if (!response.ok) {
return Effect.fail(new HttpError());
}
return Effect.succeed(response);
};
const getResponseText = async (response: Response) => {
return await response.text();
};
const fetchText = (input: RequestInfo, init?: RequestInit) =>
pipe(
Effect.succeed([input, init]),
fetchEffect,
handleHttpError,
getResponseText
);
import { Effect, pipe } from "effect";
class FetchError extends Error {
readonly _tag = "FetchError";
}
class HttpError extends Error {
readonly _tag = "HttpError";
}
const getUrl = (input: RequestInfo) =>
typeof input === "string" ? input : input.url;
const fetchEffect = Effect.tryPromise({
try: () => fetch(input, init),
catch: e =>
new FetchError(
`Failed to fetch url: ${getUrl(input)} with error: ${
e instanceof Error && e.message
}`
)
});
const handleHttpError = (response: Response) => {
if (!response.ok) {
return Effect.fail(new HttpError());
}
return Effect.succeed(response);
};
const getResponseText = async (response: Response) => {
return await response.text();
};
const fetchText = (input: RequestInfo, init?: RequestInit) =>
pipe(
Effect.succeed([input, init]),
fetchEffect,
handleHttpError,
getResponseText
);