Effect CommunityEC
Effect Community3y ago
4 replies
kristo

Creating an Effect for Data Fetching and Conversion

Hi all, I am trying to make my first effect : ) and running into a roadblock. I want to effectify my data fetching, so I am starting by making an effect to:
1. Fetch some url using fetch and taking in the same arguments as fetch
2. Convert errors to failures
3. Convert the response to text

This is what I have so far, but I can't figure out how to make an effect that takes the arguments input and
init
:

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
  );
Was this page helpful?