Skip to Content
Endpoints

Share endpoints as a service

Bind a record of endpoint definitions to a client once, and share them as an Effect service.

This page shows you how to bind your endpoint definitions to a client with Fetch.Endpoints, so code anywhere in your app can call them through one service.

Declare the service

Fetch.Endpoints binds a record of definitions to a client and shares them as a service, the way Fetch.Service does for the client. It takes the service's id, the client's service and the record:

import * as  from "effect/Effect";
import * as  from "effect/http/FetchHttpClient";
import * as  from "effect/Layer";
import * as  from "effect/Schema";

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

declare const : () => <string | null>;

const  = .({ : ., : . });
const  = .({ : . });
const  = .({
  : .,
  : .,
});
const  = .({ : . });

const  = .("GET /users/:id", { :  });
const  = .("GET /users", { : .() });
const  = .("POST /users", {
  : ,
  : ,
});
const  = .("POST /auth/login", {
  : ,
  : ,
});

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

export class  extends .<>()("UserApi", , {
  : ,
  : ,
  : ,
  // A [definition, options] pair: logging in sends no token.
  : [, { : { : false } }],
}) {}

export const  = .(function* () {
  const  = yield* ;
  const  = yield* .({ : { : "Ada" } });
  const  = yield* .({ : { : 2 } });
  const  = yield* .({ : { : . } });
  return { ,  };
});

export const  = ..(
  .(.),
  .(.),
);

What the class gives you

Like Fetch.Service, the class gives you three things:

  • UserApi is the service. yield* UserApi gives the endpoints, each typed with the client's plugins, defaultError and statusErrors.
  • UserApi.layer binds them to the client once, when it's built. It needs the client's service, here Api. The client can also be a service you wrote by hand.
  • UserApi.definitions is the record you passed, frozen. You can read it when the module loads.

Layer.provideMerge keeps Api in the layer's output, so code can still yield* Api for one-off calls.

Give options that depend on the client

A definition doesn't know its client, so the following options depend on the binding:

  • Plugin overrides are given when binding, as in the login pair in the example, where they're checked against the client's plugins. A definition takes no plugins.
  • A definition without an error schema uses the defaultError of the client it's bound to.
  • Headers can be given in both. The binding's win over the definition's.

What's next

On this page