Filter responses with effect

We need to filter Response based on its .ok value.

If you type Effect.f ("filter") you will quickly find some .filter functions.

Just by typing Effect.f you can already find the filtering functions that we need
Just by typing Effect.f you can already find the filtering functions that we need

In our case we want to filter that the result is ok, or fail with an error if it's not.

We therefore use filterOrFail:

  • In the first parameter we get Response and return response.ok
  • The second parameter is a custom error type in case the predicate fails (.ok === false)

When working with effect, any new step should be added to pipe.

We are building a series of operations by adding composable blocks to a single pipe.

const main = fetchRequest.pipe(
  Effect.filterOrFail(
    (response) => response.ok,
    (): FetchError => ({
      _tag: "FetchError",
    })
  ),
  Effect.flatMap(jsonResponse),
  Effect.catchTags({
    FetchError: () => Effect.succeed("Fetch error"),
    JsonError: () => Effect.succeed("Json error"),
  })
);

filterOrFail will return the given error (FetchError) when response.ok is false, otherwise it keeps Response as success value.

Effect Playground