Skip to Content
Clients

Derive a client

Make a client from another, with a different base URL or one more header.

Sometimes you need a second client that's almost the same as the first: the same API under another version, or the same backend with one more header. Rather than repeat the config, you spread the first client's config into the second and change what differs. This page shows how, and what happens to each option you change.

Spread the first client's config

Spread the first class's config into a second class, then set the options that differ:

import * as  from "effect/Schema";

import {  } from "@monarcode/effetch";
import {  } from "@monarcode/effetch/plugins";

export class  extends .<>()("Api", {
  : "https://api.example.com/v1",
  : .({ : . }),
  : [()],
}) {}

export class  extends .<>()("ApiV2", {
  ....,
  : "https://api.example.com/v2",
}) {}

ApiV2 keeps the plugins, the defaultError and the statusErrors of Api, so its client has the same type. A function that takes Effect.Success<typeof Api> takes an ApiV2 client too.

Give the second class its own id, as "ApiV2" here. With the same id, the two classes would be the same service.

Change an option

Any option you set replaces the first client's. It isn't merged with it.

To add a header and keep the first client's, spread Api.config.headers before your own:

import {  } from "@monarcode/effetch";

export class  extends .<>()("Api", {
  : "https://api.example.com",
  : { "x-app": "todos" },
}) {}

export class  extends .<>()("WebApi", {
  ....,
  : { ....., "x-client": "web" },
}) {}

A header you list after the spread wins over one of the same name from Api.config.headers, whatever its case.

To add a plugin, list the plugins again. Keep the ones both clients share in constants, so both lists hold the same plugins:

import {  } from "@monarcode/effetch";
import { ,  } from "@monarcode/effetch/plugins";

const  = ();

export class  extends .<>()("Api", {
  : "https://api.example.com",
  : [],
}) {}

export class  extends .<>()("LoggedApi", {
  ....,
  : [, ()],
}) {}

A client with different plugins has a different type, since plugins add errors and per-call options. The same goes for a different defaultError or statusErrors. Type the second client as Effect.Success<typeof LoggedApi>.

You could also write [...(Api.config.plugins ?? []), logger()], but Api.config.plugins can be undefined in its type, so the list's type becomes a choice between two lists rather than the one you meant.

What's next

On this page