Database
Give handlers a database (or anything else) through a typed deps object, and turn ORM errors into HTTP errors.
hono-bento doesn't wrap your database. Use Prisma, Drizzle, Kysely or a raw driver as you normally would. The framework adds two things:
deps: a typed object every handler receives, built per request by a provider you pass tomountSpecs. Put your database client in it.mapError: turns the errors your ORM throws for client mistakes (a missing record, a duplicate value) into404s and409s instead of500s.
Register the type
Declare what handlers receive once, in the app:
import type { Database } from '@todos/db';
import type { ChangeFeed, TodoChange } from './changes';
export interface Deps {
db: Database;
/** Changes to todos, which the todos feature publishes and its `changes` stream sends. */
todoChanges: ChangeFeed<TodoChange>;
}
declare module 'hono-bento' {
interface Register {
deps: Deps;
}
}Every handler's deps now has this type, with nothing to pass to
defineHandler. Once it's registered, mountSpecs requires a deps
provider, so an app can't start without its database wired in. Forgetting it
is a type error.
One registration per program
Register is augmented for the whole TypeScript program. If one monorepo has two hono-bento APIs with different deps,
typecheck each app with its own tsconfig.json.
Provide it
import type { Database } from '@todos/db';
import { Hono } from 'hono';
import { mountSpecs } from 'hono-bento';
import { mapPostgresError, mapPrismaError } from 'hono-bento/db';
import { roleAuthorizer, strategies } from './auth';
import { createChangeFeed } from './changes';
import type { Deps } from './deps';
import { specs } from './specs';
export function createApp({ db }: { db: Database }) {
// Built once per app, and the same for every request.
const deps: Deps = { db, todoChanges: createChangeFeed() };
const app = new Hono();
mountSpecs(app, specs, {
strategies,
authorizer: roleAuthorizer,
deps: () => deps,
mapError: [mapPrismaError, mapPostgresError],
});
return app;
}The app receives its database rather than importing it. server.ts connects
and passes the client in:
import { createDatabase, databaseUrl } from '@todos/db';
import { createApp } from './app';
const db = createDatabase(databaseUrl());
const app = createApp({ db });Per-request databases
The provider runs after authentication, with the identity, so it can choose a database per caller: a tenant's database, or live versus test data.
deps: ({ identity }) => ({ db: identity?.livemode ? liveDb : sandboxDb }),It runs once per request, and only for requests that passed authentication.
It may be async, and an HttpError it throws is sent like any other.
Use it
Handlers pass deps.db to their feature's store, which holds the queries:
export const updateTodo = defineHandler<Session, typeof contracts.update>(
async ({ deps, identity, params, body, respond }) => {
const { todo, ownerId } = await store.update(deps.db, ownerScope(identity), params.id, body);
deps.todoChanges.publish({ type: 'updated', ownerId, todo });
return respond(200, todo);
}
);import type { Database, Todo as TodoRow } from '@todos/db';
import type { Todo, TodoUpdate } from '@todos/schemas/todos';
import type { Owner } from '../../access';
/** Rows never leave the store: each one is mapped to the API's wire shape. */
export function toTodo(row: TodoRow): Todo {
return {
object: 'todo',
id: row.id,
title: row.title,
done: row.done,
project: row.projectId,
created: Math.floor(row.createdAt.getTime() / 1000),
};
}
export const store = {
// `owner` scopes the update to rows the caller may change: see Auth's resource-level authorization.
async update(db: Database, owner: Owner, id: string, input: TodoUpdate): Promise<{ todo: Todo; ownerId: string }> {
const row = await db.todo.update({ where: { id, ...owner }, data: input });
return { todo: toTodo(row), ownerId: row.ownerId };
},
};Two rules keep this clean, and both are checked:
- Only
store.tstouches the database, and only through types. The connection is made inserver.tsand in tests, never in a feature, so tests can hand the app any database. Features never read the environment either.hono-bento checkenforces both. - Storage models never reach a response. The store maps each row to its
@todos/schemasshape, so renaming a column can't change the API by accident.respondonly accepts the wire shape, so passing it a row (with itsDates) is a type error, andvalidateResponseschecks every response at runtime.
Error mapping
import { mapPostgresError, mapPrismaError } from 'hono-bento/db';
mountSpecs(app, specs, { ..., mapError: [mapPrismaError, mapPostgresError] });| Mapper | Error | Response |
|---|---|---|
mapPrismaError | P2025: the record an update, delete or …OrThrow needed | 404 not_found |
P2002: unique constraint | 409 conflict, code unique_violation | |
P2003: foreign key constraint | 409 conflict, code foreign_key_violation | |
mapPostgresError | SQLSTATE 23505: unique violation | 409 conflict, code unique_violation |
23503: foreign key violation | 409 conflict, code foreign_key_violation | |
23502 (not null), 22P02 (malformed value, such as a UUID) | 400 invalid_request |
mapPostgresError works with anything on Postgres: pg, postgres.js, PGlite,
and the ORMs built on them (Drizzle, Kysely, TypeORM, MikroORM). It looks
through error.cause, since Drizzle wraps the driver's error. Neither mapper
imports a database library.
When it can, the 409 names the field in param, read from the error's
metadata. Messages are generic: they never include SQL, constraint names or
values. The original error still goes to your logger, as cause.
With P2025 mapped, a handler doesn't need to check that the record exists
before updating or deleting it. Let the ORM throw. A findUnique returns
null rather than throwing, so a retrieve handler still throws
HttpError.notFound itself.
Transactions
A feature owns its operations, not its tables. When an operation changes rows
that another feature serves, its store writes them through deps.db like any
other row, and never imports the other feature. When the write touches more
than one table, it runs in one transaction.
In the example, deleting a project deletes its todos. The projects feature's store does both:
async remove(db: Database, owner: Owner, id: string): Promise<number> {
return db.$transaction(async (tx) => {
const { count } = await tx.todo.deleteMany({ where: { projectId: id } });
await tx.project.delete({ where: { id, ...owner } });
return count;
});
},The project's delete is scoped to the caller. For anyone else's project it
throws P2025, the handler answers 404, and the transaction rolls the todos
back. The schema declares onDelete: Restrict, so the database refuses to
orphan todos even if a store forgets them.
Prisma's nested writes are atomic too: creating a project with
todos: { create: [...] } inserts all or nothing, with no explicit
transaction. Other ORMs have their own (db.transaction() in Drizzle and
Kysely). Keep the transaction inside one store function, so a handler never
holds one open.
Testing
Because the app receives its database, a test builds the app with whichever database it wants. No module mocking is needed:
import { createApp } from '../../app';
import { testDb } from '../../test-db';
const app = createApp({ db: testDb, log: false });
// Each test starts from an empty table.
beforeEach(async () => {
await testDb.todo.deleteMany();
});The example's tests run against Postgres: the server at DATABASE_URL when
it's set (Docker locally, a service container in CI), else
PGlite, Postgres compiled to WebAssembly, started in the
test process and served on a local port, so a fresh clone runs every test with
no Docker. Each test run gets its own schema. A test preload
(test-setup.ts, wired up in bunfig.toml) creates and migrates
test_<pid>_<time> before any test file loads, and drops it after the last
one. So tests can insert and delete freely, two runs never see each other's
rows, and the development database is never touched.
There's no skipping: either way the tests run against Postgres. A suite that
quietly skips its database tests would pass without testing anything. CI still
runs them on a real Postgres server, which is what production runs. PGlite's
clock ticks in milliseconds, so don't let a test depend on two rows getting
different now() timestamps.
Beyond the database
deps can hold anything handlers need that you'd want to swap in tests: a
cache, a queue, an email sender, a clock.
export interface Deps {
db: Database;
mailer: Mailer;
now: () => Date;
}