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:
UserApiis the service.yield* UserApigives the endpoints, each typed with the client's plugins,defaultErrorandstatusErrors.UserApi.layerbinds them to the client once, when it's built. It needs the client's service, hereApi. The client can also be a service you wrote by hand.UserApi.definitionsis 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
loginpair in the example, where they're checked against the client's plugins. A definition takes noplugins. - A definition without an
errorschema uses thedefaultErrorof the client it's bound to. - Headers can be given in both. The binding's win over the definition's.
What's next
- Call an endpoint: see what each call takes, and how to bind endpoints without a service.
- Structure an app: decide where clients and endpoints live as your app grows.
- Test with a fake backend: serve your endpoints from a fake backend in tests.