rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

Two ways to compose#

A Rhythm module is a self-contained pipeline with its own startup phase. A host composes it one of two ways, depending on when it should run:

mount(module)#
Request time. The module runs on every call with a copy of the host's context. What it derives stays inside it, and the host's later middleware always runs afterwards.
include(module, pick?)#
Startup time. The module runs once, when registered, with the host's startup context as its input. pick copies chosen fields into the host's startup context, and the module's stop() becomes one of the host's cleanups.

Mount a module#

A mounted module may derive whatever it likes; none of it reaches the host. mount checks at compile time that the host can supply the module's input, and widens the host's own input when it cannot.

TypeScript
import { Rhythm, derive, mount } from "@rhythmjs/rhythm";

const identity = new Rhythm<{}, { userId: string }>({ name: "identity" }).use(
  derive((ctx) => ({ user: { id: ctx.userId, name: "Ada" } })),
);

const app = new Rhythm().use(mount(identity)).use((ctx) => {
  console.log(ctx.userId); // typed: mount widened the host's input
  console.log(ctx.user); // type error: derived fields do not leak out of a mount
});

await app.callback()({ userId: "u1" });

mount(module) widens the host's input automatically: the host above needs { userId: string } from its caller even though it never declared it. Pass a condition to run the module only for some calls: mount(module, (ctx: { userId: string }) => ctx.userId !== "").

Include a module#

Use include for modules that build long-lived values. Without pick, no fields cross back, so the parent only inherits the cleanup.

TypeScript
const database = new Rhythm({ name: "database", type: "service" }).register(
  decorate(async () => ({ db: await createDb() })),
  (ctx) => ctx.db.close(),
);

const app = new Rhythm()
  .register(include(database, (child) => ({ db: child.db })))
  .use((ctx) => ctx.db.run("select 1"));

The parent's startup context must satisfy the child's input type, so a module that needs { db } can be included only after something has added it.

Mount always continues#

A mounted plugin is part of the host's chain, but not the end of it. After the plugin runs, mount always calls next(). A router that did not match leaves the context untouched, so a catch-all registered after it only sees what nothing answered; a router that did match has already written the response, so check ctx.response if a later middleware should act only on unmatched requests, as below.

TypeScript
const app = new Rhythm()
  .use(mount(productsRouter))
  .use(mount(usersRouter))
  .use((ctx) => {
    if (ctx.response.body === null) ctx.json({ message: "Not Found" }, 404);
  });

An untouched response already becomes a plain 404 Not Found in toFetchHandler, so a fallback like this is only needed for a custom body.

Wrapped errors#

Errors thrown inside a mounted plugin are wrapped as mounted <type> "<name>" failed with the original error as cause. An included module that fails to start is wrapped as included module "<name>" failed. Errors thrown by the host's later middleware are not wrapped: they are not the plugin's failure. The name and type come from the plugin's options (new RhythmRouter({ name: "users" }) gives mounted router "users" failed; with no name the label is "anonymous").

Because the wrapped error no longer carries the status of an HttpError, put filter() on the router that throws it rather than on the host. errorToResponse also looks through the cause chain for a declared status.

Routers, ws, cron and clis are pipelines#

RhythmRouter, RhythmWs, RhythmCron and RhythmCli extend the same Pipeline base as Rhythm: each has use(), but none has a startup phase. Startup work belongs to the Rhythm host, and the host mounts them all the same way.

TypeScript
const app = new Rhythm()
  .register(decorate(() => ({ db })))
  .use(mount(router))
  .use(mount(ws));

app.register(startCron(cron)); // cron is started at startup instead of mounted

The host's startup values are on the context of everything mounted in it, which is how a controller typed RhythmRouter<{ db: Db }> receives ctx.db.

Inspect the app#

Middleware is opaque, so tooling cannot ask a function what it is. Instead, a middleware or register callback can be tagged with the object it was built from using withSource(fn, source). mount() and include() tag themselves with the plugin they wrap, so app.sources lists the leaf plugins (routers, clis, anything tagged) below the app in order, with each Rhythm module expanded in place. app.parent is the pipeline a plugin was adopted by.

TypeScript
const usersModule = new Rhythm({ name: "users" }).use(mount(usersRouter));

const appModule = new Rhythm({ name: "app" })
  .use(mount(usersModule))
  .use(mount(healthRouter));

appModule.sources; // [usersRouter, healthRouter]
usersModule.sources; // [usersRouter]
usersModule.parent; // appModule

A pipeline sees only its own scope: a module mounted in apiModule inspects apiModule and below, never its siblings. This is how the OpenAPI and help modules find what to document. The OpenAPI page shows it in use.