Tutorial · Step 3 of 12
Services & startup context
Business logic in factories, built once at startup and closed by whoever created it.
On this page
Factories over classes#
Business logic lives in services: plain objects or factory functions, never classes with decorators. A factory takes its dependencies as arguments and returns the service object; the service's type is derived, not declared twice:
// src/notes/notes.service.ts
export interface Note {
id: string;
title: string;
content: string;
}
export function createNotesService(store: Map<string, Note> = new Map()) {
return {
list(): Note[] {
return [...store.values()];
},
get(id: string): Note | undefined {
return store.get(id);
},
create(input: { title: string; content?: string }): Note {
const note: Note = { id: crypto.randomUUID(), title: input.title, content: input.content ?? "" };
store.set(note.id, note);
return note;
},
update(id: string, patch: { title?: string; content?: string }): Note | undefined {
const note = store.get(id);
if (!note) return undefined;
const updated = { ...note, ...patch };
store.set(id, updated);
return updated;
},
remove(id: string): boolean {
return store.delete(id);
},
};
}
export type NotesService = ReturnType<typeof createNotesService>;Add once, use everywhere#
A Rhythm app carries a startup context: values built once, before the first request. register(decorate(() => ({ ... }))) runs right away and adds the returned fields to that context; every request then starts from a copy of it, so everything mounted in the app sees the values on ctx. Services are built eagerly, in plain code — dependency injection is a function argument:
// src/app.module.ts
export const appModule = new Rhythm({ name: "app" })
.register(decorate(() => ({ appService })))
.register(decorate(() => ({ notesService: createNotesService() })))
.use(mount(appController))
.use(mount(notesController));Nothing is declared twice: the app's type grows with each decorate, and a step can read only what an earlier step added. A later register(decorate(({ notesService }) => ...)) sees the service above it, which is how a statsService would be built from notesService.
The controller declares what it needs in its context type and reads it off ctx — the type-level equivalent of constructor injection. If the app never supplies it, the app no longer type-checks where it is served: toFetchHandler(appModule) in main.ts rejects an app whose context lacks notesService, so forgetting the decorate is a compile error, not a runtime surprise:
// src/notes/notes.controller.ts
import { RhythmRouter } from "@rhythmjs/router";
import type { NotesService } from "./notes.service";
import { json } from "@rhythmjs/router/response";
export type NotesContext = { notesService: NotesService };
export const notesController = new RhythmRouter<NotesContext>({ name: "notes" })
.get("/api/notes", (ctx) => {
json(ctx, ctx.notesService.list());
});The in-memory Map and routes of the previous step move into the service; the controller only translates between HTTP and service calls.
Registration is sequential#
register callbacks run in the order you write them, and a callback waits for every earlier one to finish, including async ones. A step that loads something asynchronous can therefore be followed by a step that depends on it, with no manual awaiting and no undefined surprises:
export const appModule = new Rhythm({ name: "app" })
.register(decorate(async () => ({ seed: (await Bun.file("seed.json").json()) as Note[] })))
.register(
decorate(({ seed }) => ({
notesService: createNotesService(new Map(seed.map((note) => [note.id, note]))),
})),
)
.use(mount(notesController));The same holds for include(...) of an async module, which the next pages use constantly. If a registration fails, the later ones are skipped and the first request rejects with the original error, so a half-built app never serves traffic.
Closing resources#
Whoever creates a resource closes it, and register takes a second argument for exactly that: a cleanup that runs when the app is stopped, in reverse order of registration. It receives the startup context, so it can reach what the registration added. A service that holds something open exposes close():
const database = createDatabase(url);
export const appModule = new Rhythm({ name: "app" }).register(
decorate(() => ({ db: database })),
() => database.close(), // runs on appModule.stop()
);
// main.ts, on SIGTERM
await appModule.stop();If the app is built from child modules with include() (next step), the child's own cleanups are registered with the parent automatically, so one stop() closes the whole tree.
Per-request values#
Startup values are per-application. For per-request values — the current user, a request id, a scoped transaction — use derive(): a middleware whose return value extends the context, with the extension visible to the type system downstream:
import { derive } from "@rhythmjs/rhythm";
import { json } from "@rhythmjs/router/response";
const withRequestMeta = derive((ctx: { request: Request }) => ({
startedAt: Date.now(),
ua: ctx.request.headers.get("user-agent") ?? "unknown",
}));
new RhythmRouter().use(withRequestMeta).get("/me", (ctx) => {
json(ctx, { ua: ctx.ua }); // typed
});The rule of thumb: decorate() for things built once and shared, derive() for things computed per request. Both put values on ctx; only their lifetimes differ.