Data
Databases on Rhythm
Rhythm ships no database layer on purpose — the kernel's startup context is already the right shape for one. Four recipes, one identical pattern.
On this page
A recipe, not a package#
There is no @rhythmjs/data. A database connection is just a resource with a lifetime, and the kernel's startup context is the right place to hand it to the app: create the connection once at startup with decorate, and close it in the cleanup callback you pass to register, which runs on app.stop(). Every ORM plugs into that the same way, so this section documents the pattern once and then shows it four times: Drizzle, Prisma, and MikroORM on PostgreSQL, plus the native MongoDB driver. Each page is backed by a complete runnable app in rhythmjs/examples, all serving the same notes CRUD API.
The database module#
The connection lives in a small Rhythm module. decorate adds the client to the startup context (the callback may be async, as with Mongo's connect or MikroORM's init), and the second argument of register is the cleanup that releases it.
// src/database.ts
import { PrismaClient } from "@prisma/client";
import { Rhythm, decorate } from "@rhythmjs/rhythm";
export const databaseModule = new Rhythm({ name: "database" }).register(
decorate(() => ({ prisma: new PrismaClient() })),
({ prisma }) => prisma.$disconnect(),
);Anything that must be closed but is not needed by the app, such as Mongo's MongoClient behind its Db, can still go on the context and be closed by the cleanup. Only what you decorate is visible to later modules.
The app module#
A feature module pulls the connection out of the database module with include(databaseModule, pick), which runs the child once at startup and copies the picked fields into the parent's startup context. The service is then another decorate. The app module includes the feature module and mounts its router.
// src/notes/notes.module.ts
export const notesModule = new Rhythm({ name: "notes" })
.register(include(databaseModule, ({ prisma }) => ({ prisma })))
.register(decorate(({ prisma }) => ({ notesService: createNotesService(prisma) })));// src/app.module.ts
export const appModule = new Rhythm({ name: "app" })
.register(include(notesModule, ({ notesService }) => ({ notesService })))
.use(mount(notesController));include also registers the child's stop() as cleanup, so stopping the app closes the database. Small apps can skip the extra modules: the Drizzle and MikroORM pages decorate the client directly in the app module and derive the service from it. The entrypoint serves the app and stops it on shutdown:
// src/main.ts
const server = Bun.serve({ port, fetch: toFetchHandler(appModule) });
async function shutdown(): Promise<void> {
await server.stop();
await appModule.stop();
process.exit(0);
}
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);register callbacks run as soon as they are registered, and the first request waits for any that are still pending, so an async connection is ready before a handler sees it. Cleanups run only when you call appModule.stop(), so wire it to your signals as above.
The service factory#
Persistence lives in one factory — createNotesService(db) — that the notes module builds from the connection in the startup context. The service owns every query and answers in plain terms: list, get (a note or nothing), create, update (the new note or nothing), remove (a boolean). ORM types stop at this boundary: Prisma's P2025 becomes null, Mongo's ObjectId documents become id: string DTOs, and controllers stay identical across all four stacks.
Contracts at the edges#
Request and response shapes are zod schemas in src/notes/notes.schema.ts, enforced by @rhythmjs/middleware: validate("body", …) types the parsed body onto ctx.valid.body, intercept(…) checks every 2xx response against the contract (and strips unknown fields on the way out), and the filter() on the router renders thrown HttpErrors, and anything unexpected, as JSON failures.
// src/notes/notes.controller.ts
export const notesController = new RhythmRouter<NotesContext>()
.use(filter())
.use(intercept(notesResponseSchema))
.get("/api/notes", async (ctx) => {
json(ctx, await ctx.notesService.list());
})
.get("/api/notes/:id", async (ctx) => {
const note = await ctx.notesService.get(ctx.params.id);
if (!note) throw new HttpError(404, "Note not found");
json(ctx, note);
})
.post("/api/notes", validate("body", createNoteSchema), async (ctx) => {
json(ctx, await ctx.notesService.create(ctx.valid.body), 201);
});Migrations#
Schema changes are checked-in files applied by an explicit db:migrate script, never by the app at boot. Each ORM keeps its own convention: Drizzle generates SQL into drizzle/ with drizzle-kit, Prisma keeps prisma/migrations/ applied by migrate deploy, MikroORM runs Migration classes from src/migrations/ through its Migrator, and MongoDB — schemaless — has no migration step at all, just index creation in the database factory.
The recipes#
Beyond the shared shape, each page demonstrates one thing its stack does differently:
- Drizzle: Bun's native
SQLclass as the driver — no driver dependency — and the pool closed through the instance's$client. - Prisma: a generated client in a database module, and mapping
P2025error codes to plain not-found answers. - MikroORM: decorator-free
defineEntityentities and a forkedEntityManagerper operation. - MongoDB: no ORM at all — documents mapped to DTOs at the service boundary, with zod as the only schema.