rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

Install#

The generated client is a runtime dependency; the prisma CLI is a dev tool. The schema lives in prisma/schema.prisma, and the model maps to the same notes table the other recipes use.

Shell
bun add @prisma/client zod @rhythmjs/rhythm @rhythmjs/router @rhythmjs/middleware
bun add -d prisma
TypeScript
// prisma/schema.prisma
model Note {
  id        String   @id @default(uuid())
  title     String
  content   String   @default("")
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")

  @@map("notes")
}

The database module#

PrismaClient manages its own pool, so the module is short: decorate creates the client at startup and the cleanup calls $disconnect() when the app stops. Passing datasourceUrl keeps the runtime independent of the .env file the CLI reads.

TypeScript
// src/database.ts
import { PrismaClient } from "@prisma/client";
import { Rhythm, decorate } from "@rhythmjs/rhythm";

const databaseUrl = process.env.DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/notes_prisma";

export const databaseModule = new Rhythm({ name: "database" }).register(
  decorate(() => ({ prisma: new PrismaClient({ datasourceUrl: databaseUrl }) })),
  ({ prisma }) => prisma.$disconnect(),
);

Not-found at the boundary#

Prisma throws P2025 when update or delete misses. The service catches exactly that code and answers with null / false, so the controller decides the HTTP shape — it throws HttpError(404) and the filter() boundary renders it. Everything else propagates and becomes a 500.

TypeScript
// src/notes/notes.service.ts
function isRecordNotFound(error: unknown): boolean {
  return error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2025";
}

export function createNotesService(prisma: PrismaClient) {
  return {
    list: () => prisma.note.findMany({ orderBy: { createdAt: "desc" } }),
    get: (id: string) => prisma.note.findUnique({ where: { id } }),
    create: (input: CreateNoteInput) => prisma.note.create({ data: input }),
    async update(id: string, patch: UpdateNoteInput) {
      try {
        return await prisma.note.update({ where: { id }, data: patch });
      } catch (error) {
        if (isRecordNotFound(error)) return null;
        throw error;
      }
    },
    async remove(id: string) {
      try {
        await prisma.note.delete({ where: { id } });
        return true;
      } catch (error) {
        if (isRecordNotFound(error)) return false;
        throw error;
      }
    },
  };
}

Wiring the module#

The notes module includes the database module, picking out prisma, and decorates the service on top of it. The app module includes the notes module and mounts the router. include registers each child's stop() as cleanup, so appModule.stop() disconnects Prisma.

TypeScript
// src/notes/notes.module.ts
export const notesModule = new Rhythm({ name: "notes" })
  .register(include(databaseModule, ({ prisma }) => ({ prisma })))
  .register(decorate(({ prisma }) => ({ notesService: createNotesService(prisma) })));
TypeScript
// src/app.module.ts
export const appModule = new Rhythm({ name: "app" })
  .register(include(notesModule, ({ notesService }) => ({ notesService })))
  .use(mount(notesController));

The controller is a RhythmRouter with full paths (/api/notes, /api/notes/:id). filter() on the router renders thrown HttpErrors, validate("body", …) checks bodies with zod and intercept(…) checks responses. src/main.ts serves with Bun.serve({ port, fetch: toFetchHandler(appModule) }) and calls appModule.stop() on shutdown.

Migrations#

Checked-in SQL lives under prisma/migrations/. prisma migrate deploy applies pending migrations and nothing else — it does not regenerate the client, so generation is its own step. Author new migrations with prisma migrate dev against a development database.

Shell
bun run db:generate      # prisma generate
bun run db:migrate       # prisma migrate deploy
bun run db:migrate:dev   # prisma migrate dev — author a new migration

Where to next#

The shared pattern is introduced in the overview; the first concrete recipe is Drizzle. MikroORM adds a unit of work per request; MongoDB drops the ORM entirely. The full app is examples/prisma-postgres.