Skip to Content
Plugins

Plugin recipes

Copy a plugin that signs out on a 401, or one that sets a deadline with its own error.

These plugins solve common problems, and you can copy them into your app. Each one shows a different part of the plugin API: hooks that need a service and add an error, and a wrap with an option calls can override.

Sign out on a 401

The classic plugin: send the session's token, and when the API answers 401, sign out and fail with a typed SessionExpired. To renew the token instead, see Refresh a token.

The plugin reads the token from a Session service in onRequest, and signs out in onResponse:

import * as  from "effect/Context";
import * as  from "effect/Data";
import * as  from "effect/Effect";
import * as  from "effect/http/HttpClientRequest";

import {  } from "@monarcode/effetch";

export class  extends .("SessionExpired")<{}> {}

export class  extends .<
  ,
  {
    readonly : .<string | undefined>;
    readonly : .<void>;
  }
>()("Session") {}

export const  = .({
  : "auth",
  : () =>
    .(function* () {
      const  = yield* ;
      const  = yield* .;
      return  === 
        ? 
        : .(, );
    }),
  : () =>
    .(function* () {
      if (. !== 401) {
        return ;
      }
      const  = yield* ;
      yield* .;
      return yield* new ();
    }),
});

// Api.layer now needs Session; calls fail with SessionExpired too.
export class  extends .<>()("Api", {
  : "https://api.example.com",
  : [],
}) {}

Set a deadline with its own error

A wrap that adds its own error, with an option calls can override:

import * as  from "effect/Data";
import * as  from "effect/Effect";
import * as  from "effect/http/HttpClient";

import {  } from "@monarcode/effetch";

export class  extends .("TooSlow")<{
  readonly : string;
}> {}

export const  = .({
  : "deadline",
  : { : 5000 },
  : (, ) =>
    .(, (, ) =>
      .(function* () {
        const {  } = yield* ;
        return yield* .(, {
          : ,
          : () => .(new ({ : . })),
        });
      }),
    ),
});

What's next

On this page