Refactoring Imperative Effect Code to Functional Style in TypeScript

Hi everyone, I've new in Effect, I'm understand very well how to write Effect in imperative way using Effect.gen() function, it's very nice,
I can transform from Promise-based function into generator-based function.

I've curious how to refactor that code to be more functional, or I don't need do it??

const fetchTester = Effect.gen(function*() {
  const prefixUrl = "https://jsonplaceholder.typicode.com";
  console.log(`Fetching Prefix url: "${prefixUrl}"...\n`);
  for (
    const url of [
      `${prefixUrl}/todos/1`, // Fetch Result
      `${prefixUrl}xx/todos/1`, // RequestFailError
      `${prefixUrl}/todos/-2`, // FetchError
      `${prefixUrl}/todos/1?variant=invalidJson` // InvalidJsonError
    ]
  ) {
    const cleanedUrl = url.replace(prefixUrl, "");
    yield* safeFetch(url).pipe(
      Effect.tap((value) => Effect.log(`Fetch Result (url="${cleanedUrl}"): => ${JSON.stringify(value)}`)),
      Effect.catchTags({
        "FetchError": (error) => Effect.logError(`Failed to fetch (url="${cleanedUrl}"): => ${error}`),
        "InvalidJsonError": (error) => Effect.logError(`Invalid JSON (url="${cleanedUrl}"): => ${error}`),
        "RequestFailError": (error) => Effect.logError(`Request failed (url="${cleanedUrl}"): => ${error}`)
      }),
      Effect.catchAll((error) => Effect.succeed(Effect.logError(`Unknown error (url="${cleanedUrl}"): => ${error}`)))
    );
  }
});


Here is the full code: https://tsplay.dev/WKZ0pm
Was this page helpful?