Structure an app
Lay out clients and endpoints in a small app, a feature-sliced app and an app with several backends.
Your first few calls can live anywhere. As the app grows, you have to decide where the client goes, where the endpoints go, and how the rest of the code reaches them. This page shows three layouts that work, from a small app to one that talks to several backends, so you can pick the one that fits.
What every layout has in common
Whichever layout you pick, two things stay the same:
- The client is declared once, as a service, with its base URL, error body and plugins.
- Endpoints are bound to it once, in a layer, when the app starts. Code that makes calls gets the bound endpoints from a service, and never binds them itself.
The rest is up to you. These layouts are patterns, not rules, and Effetch works the same way whichever you use.
A small app
In a small app, keep the client in one file, and each area's endpoints in
its own file, as a Fetch.Endpoints class. One layer puts them together:
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";
const = .({ : ., : . });
const = .({ : . });
const = .({
: .,
: .,
});
const = .({ : . });
const = .({ : ., : . });
// api.ts
export class extends .<>()("Api", {
: "https://api.example.com",
: [({ : "token" })],
}) {}
// users.ts
export class extends .<>()("Users", , {
: .("GET /users/:id", { : }),
: .("POST /users", { : , : }),
: [
.("POST /auth/login", {
: ,
: ,
}),
{ : { : false } },
],
}) {}
// todos.ts
export class extends .<>()("Todos", , {
: .("GET /todos", { : .() }),
}) {}
// layer.ts
export const = .(., .).(
.(.),
.(.),
);
// anywhere
export const = .(function* () {
const = yield* ;
const = yield* ; // for one-off calls
const = yield* .({ : { : 1 } });
yield* .("/users/:id/ping", { : { : . } });
return ;
});login turns off the bearer plugin, so logging in sends no token. That
override is checked against Api's plugins, and every endpoint's errors
are typed with Api's defaultError and statusErrors.
Layer.provideMerge keeps Api itself in the layer, for the one-off calls
that aren't worth an endpoint.
Endpoints made with api.endpoint
You may prefer to define each endpoint on the client with api.endpoint,
in one step. Then write each area as a function of the client, typed
Effect.Success<typeof Api>, so overrides and errors are still checked
against Api's plugins and defaultError.
That function makes new endpoints each time it runs, so don't call it per request. Run it once, in a layer, and share what it returns as a service:
import * as from "effect/Context";
import * as from "effect/Effect";
import * as from "effect/Layer";
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "@monarcode/effetch/plugins";
const = .({ : ., : . });
const = .({
: .,
: .,
});
const = .({ : . });
class extends .<>()("Api", {
: "https://api.example.com",
: [({ : "token" })],
}) {}
// The endpoints, made from the client
export const = (: .<typeof >) => ({
: .("GET /users/:id", { : }),
: .("POST /auth/login", {
: ,
: ,
: { : false },
}),
});
// Made once, when the layer is built, and shared as a service
const = .();
export class extends .<
,
.<typeof >
>()("Users") {}
export const = .()();Api.useSync(users) is an Effect that gets the client and calls users
with it. Layer.effect runs that Effect once, when the layer is built.
Code then gets the endpoints with yield* Users, as with a
Fetch.Endpoints class. Fetch.Endpoints writes these three steps for
you, so it's the shorter choice when your endpoints are defined with
Fetch.endpoint.
A feature-sliced app
A larger app is often split into feature modules, each with its own schemas. There, the client becomes shared infrastructure, and it imports nothing from the modules. Each module defines its endpoints next to its schemas, with no client, and binds them to the client in its data layer.
examples/app
is a complete app in this layout, with two modules and two backends. Here
are its files:
examples/app/
├── infrastructure/http/
│ ├── app-api-client.ts the main backend's client
│ ├── wallet-api-client.ts the wallet backend's client
│ └── plugins.ts plugins both clients use
├── modules/
│ ├── todos/
│ │ ├── contract/todos.ts schemas, and endpoints from Fetch.endpoint
│ │ ├── data/todo.api.ts the endpoints, bound to AppApiClient
│ │ ├── todo.layer.ts the module's layers, merged
│ │ └── public.ts what other code may import
│ └── wallet/
│ ├── application/ workflows that take more than one call
│ ├── contract/
│ ├── data/
│ ├── wallet.layer.ts
│ └── public.ts
├── runtime.ts modules, over the clients, over HttpClient
└── main.ts the program: imports modules only through public.tsThe following code puts the todos module's files in one block, each
under a comment with its path. It's shortened from the example, which has
more fields, endpoints and errors:
import * as from "effect/Config";
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";
// infrastructure/http/app-api-client.ts: how to reach the backend
export class extends .<>()(
"AppApiClient",
{ : .("APP_API_URL") },
) {}
// modules/todos/contract/todos.ts: schemas and endpoints, no client
const = .({ : ., : . });
const = .({ : . });
export const = .("GET /todos", {
: .(),
});
export const = .("GET /todos/:id", { : });
export const = .("POST /todos", {
: ,
: ,
});
// modules/todos/data/todo.api.ts: the endpoints, bound, as a service
export class extends .<>()(
"TodoApi",
,
{
: ,
: ,
: ,
},
) {}
// modules/todos/todo.layer.ts: every layer the module has
export const = .(.);
// runtime.ts: the modules, on top of the client, on top of HttpClient
export const = .(
.(.),
.(.),
);
// anywhere
export const = .(function* () {
const = yield* ;
const = yield* .({ : { : "Write docs" } });
return yield* .({ : { : . } });
});Why this layout scales
Each part of the app grows in its own place:
- The client file stays the same size, however many endpoints the app has, and it never imports a module. Dependencies point from the modules to the infrastructure.
- A module with 20 endpoints has 20 definitions in its own
contract/folder, beside their schemas, and 20 one-line entries in itsFetch.Endpointsclass indata/. When they serve separate concerns, split them into several services, each in its own file. - Every module's data service is its endpoints, as
TodoApiis here. There's one line per operation and every type is inferred, so every module'sdata/folder looks the same. - An operation that isn't one HTTP call (it combines calls, reshapes a
response or adds a domain error) is a workflow over those endpoints, in
the module's
application/folder, aswallethas. - Declare a service's interface by hand only when you need another implementation, such as an offline one or a fake for UI work, and implement it with the endpoints.
api.endpoint in this layout
api.endpoint fits this layout too. Make the endpoints in data/, and
import only the schemas from contract/. Define them with Fetch.endpoint
instead when something has to read the routes and schemas without a
client, such as a test's fake backend.
The example app does both. todos defines its endpoints with
Fetch.endpoint in contract/, and binds them with Fetch.Endpoints in
data/. wallet makes its endpoints with its client's endpoint method
in data/, and shares them as a service the way
Endpoints made with api.endpoint shows.
Several backends
When the app talks to more than one backend, declare one client for each,
with its own id, baseUrl, defaultError and plugins. Each module uses
the client of the backend it talks to, and one HttpClient layer serves
them all:
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>;
// One plugin value, shared by both clients
const = ({ : () => () });
export class extends .<>()(
"AppApiClient",
{
: "https://api.example.com",
: .({ : . }),
: [],
},
) {}
export class extends .<>()(
"WalletApiClient",
{
: "https://wallet.example.com",
: .({ : . }),
: [],
},
) {}
export const = .(
.,
.,
).(.(.));Keep the following in mind:
- Plugins are values, so one
bearercan serve several clients, asauthdoes here. - A route doesn't say which backend it's for. Plugins get the call's
route as
ctx.route(see Write a plugin). It's the method and the path as written, with no base URL, so both backends can have aGET /health. Only a route written as a full URL keeps its host. A plugin that groups by route and is shared by several clients should take the backend's name, so each client gets its own instance. - Catch a backend's
HttpErrornext to its calls, wherebodyhas that backend's error shape.
examples/backends.ts
does this in one file, and
examples/app
across modules.
What's next
- Share endpoints as a service: see everything
a
Fetch.Endpointsclass gives you. - Declare a client: declare one client per backend, with its own base URL, errors and plugins.
- Test with a fake backend: serve your endpoints from a fake backend in tests.