Tutorial · Step 8 of 12
Persistence
A real database in the startup context — pool, schema, service, CRUD.
The database as a startup resource#
A database is the canonical infrastructure module: open the pool once, add the query handle to the startup context, and give the module the cleanup that closes it. This example uses Drizzle on Bun's native SQL driver; the data recipes cover Prisma, MikroORM, and MongoDB with the same shape. The factory is plain code:
// src/database/database.ts
import { SQL } from "bun";
import { drizzle } from "drizzle-orm/bun-sql";
import * as schema from "../notes/notes.table";
export function createDatabase(url: string, max: number) {
return drizzle({ client: new SQL({ url, max }), schema });
}
export type Database = ReturnType<typeof createDatabase>;The module opens the pool with the validated settings from step 7, registers it, and owns closing it. It is created once and exported as a plain instance:
// src/database/database.module.ts
import { decorate, Rhythm } from "@rhythmjs/rhythm";
import { databaseConfig } from "../config/database.config";
import { createDatabase } from "./database";
const { url, poolSize } = await databaseConfig(); // throws on malformed config
export const database = createDatabase(url, poolSize);
export const databaseModule = new Rhythm({ name: "database" }).register(
decorate(() => ({ db: database })),
() => database.$client.close(), // whoever opened the pool closes it, when the app stops
);Schema and service#
The table definition is plain Drizzle, and the service factory from step 3 now takes the database instead of a Map. The service becomes async, so each controller handler gains an await — the routes themselves do not change:
// src/notes/notes.table.ts
import { pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
export const notes = pgTable("notes", {
id: uuid("id").primaryKey().defaultRandom(),
title: text("title").notNull(),
content: text("content").notNull().default(""),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
});
export type Note = typeof notes.$inferSelect;// src/notes/notes.service.ts
import { desc, eq } from "drizzle-orm";
import type { Database } from "../database/database";
import { notes, type Note } from "./notes.table";
import type { CreateNoteInput, UpdateNoteInput } from "./notes.schema";
export function createNotesService(db: Database) {
return {
list(): Promise<Note[]> {
return db.select().from(notes).orderBy(desc(notes.createdAt));
},
async get(id: string): Promise<Note | undefined> {
const [note] = await db.select().from(notes).where(eq(notes.id, id));
return note;
},
async create(input: CreateNoteInput): Promise<Note> {
const [note] = await db.insert(notes).values(input).returning();
return note!;
},
async update(id: string, patch: UpdateNoteInput): Promise<Note | undefined> {
const [note] = await db
.update(notes)
.set({ ...patch, updatedAt: new Date() })
.where(eq(notes.id, id))
.returning();
return note;
},
async remove(id: string): Promise<boolean> {
const deleted = await db.delete(notes).where(eq(notes.id, id)).returning({ id: notes.id });
return deleted.length > 0;
},
};
}
export type NotesService = ReturnType<typeof createNotesService>;// src/notes/notes.controller.ts — the handlers now await the service
.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);
})Wire it together#
The notes module from step 4 now includes the database module, builds its service from db, and still mounts its own controller. Because register is sequential, the decorate after the include already sees db (this relies on @rhythmjs/rhythm 0.0.21 or newer, where a registration waits for every earlier one):
// src/notes/notes.module.ts
import { decorate, include, mount, Rhythm } from "@rhythmjs/rhythm";
import { databaseModule } from "../database/database.module";
import { notesController } from "./notes.controller";
import { createNotesService } from "./notes.service";
export const notesModule = new Rhythm({ name: "notes" })
.register(include(databaseModule, ({ db }) => ({ db })))
.register(decorate(({ db }) => ({ notesService: createNotesService(db) })))
.use(mount(notesController));The app includes the same database module too. That is for lifecycle: a mounted module does not register cleanups with its parent, so without this line appModule.stop() would not close the pool. The pool exists once, however many modules include it, and is closed once:
// src/app.module.ts
export const appModule = new Rhythm({ name: "app" })
.register(include(settingsModule, ({ configService }) => ({ configService })))
.register(include(databaseModule, ({ db }) => ({ db }))) // lifecycle: closed on appModule.stop()
.register(decorate(() => ({ appService })))
.use(mount(appController))
.use(mount(notesModule));// src/main.ts
const { port } = await appConfig();
const server = Bun.serve({ port, fetch: toFetchHandler(appModule) });
process.on("SIGTERM", async () => {
await server.stop();
await appModule.stop(); // runs the cleanups in reverse order: closes the pool
process.exit(0);
});The notes module is self-contained: it declares the infrastructure it needs, and the app does not build notesService at all. Dropping the module's include is a compile error, because the decorate after it would have no db to read. The next steps replace the hand-written SIGTERM handler with gracefulShutdown.
For local development, run Postgres from a compose file bound to loopback only — never publish a dev database on all interfaces:
# compose.yaml
services:
postgres:
image: postgres:17
environment:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: notes
ports:
- "127.0.0.1:5432:5432"