rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

Two phases#

An app has a startup phase and a request phase. register() is the startup phase: it runs a callback once, in order, against the app's shared startup context, and may name a cleanup to run when the app stops. use() is the request phase: it runs on every call. Anything long-lived, such as a database connection, a client, or configuration, belongs in register().

Add values with decorate#

decorate(fn) is the typed way to add fields at startup. The returned object is merged into the startup context, and its fields are typed for everything after it. Nothing is declared twice: the type is inferred from what you return.

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

const app = new Rhythm<{}, { jobId: string }>()
  .register(
    decorate(async () => ({ db: await createDb(), logger: createLogger() })),
    (ctx) => ctx.db.close(), // cleanup: runs on stop()
  )
  .use((ctx) => {
    ctx.logger.info(`job ${ctx.jobId}`);
    return ctx.db.run(ctx.jobId);
  });

await app.callback()({ jobId: "job-1" });
await app.stop();

A callback that returns a promise is awaited: the first call waits for it, so you never serve a half-started app. A plain callback (not wrapped in decorate) works too when you only need a side effect. decorate receives the startup context so far, so a later decorate can build on an earlier one.

Merge order#

Each call builds its context as the startup values merged with the caller's input, so an input field wins over a startup value with the same name. The values are shared references, not copies. Mutating an object you added with decorate is visible to the next call, which is what you want for a connection and a hazard for request-scoped state. A derive always works on the call's own copy.

Cleanup#

register(callback, cleanup) takes the cleanup as its second argument. stop() runs the cleanups in reverse order of registration, so a dependency is closed after the things that use it. If several cleanups throw, stop() still runs all of them and rejects with an AggregateError.

TypeScript
const app = new Rhythm().register(
  decorate(() => ({ cache: createCache() })),
  (ctx) => ctx.cache.close(),
);

process.on("SIGTERM", async () => {
  await server.stop();
  await app.stop();
  process.exit(0);
});

Rhythm is AsyncDisposable, so await using app = new Rhythm()... calls stop() when the scope ends.

Share a module's values with include#

A module that builds its own dependencies can hand them to a parent with include(module, pick). The child runs once, at registration, with the parent's startup context as its input. pick copies chosen fields into the parent's startup context, and the child's stop() becomes one of the parent's cleanups.

TypeScript
import { include } from "@rhythmjs/rhythm";

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 })));

Without pick, nothing crosses back, which suits a module that only does startup work. include is how the config, health and Better Auth modules plug in. See Encapsulated modules.