schemaOf
Builds zod schemas for create and update bodies from a table’s columns, so a handler doesn’t redeclare every field.
Usage
app/orders/post.ts
import { z } from "@hono/zod-openapi";
import { schemaOf } from "app/db";
import { orders } from "./orders.table";
import { createOrder } from "./repository";
const S = schemaOf(orders);
export const schema = {
body: S.insert.pick({ customerName: true, total: true }).extend({ total: z.number().positive() }),
};
export default (c, { user, body }) => createOrder(user, body);Signature
app/db.ts
function schemaOf(table: SQLiteTable): { insert: z.ZodObject; update: z.ZodObject };Parameters
table: a table declared withsqliteTablein*.table.ts.
Returns
Two plain zod objects, so .pick, .omit, .extend and .partial work:
insert: every column except an auto-increment integer primary key. Columns with a default or that allownullare optional.update: every column, all optional.
Columns map to zod like this:
text→z.string();text(…, { enum })→z.enum(…)integer→z.number().int();real→z.number()integer({ mode: "boolean" })→z.boolean()- date columns →
z.coerce.date() - nullable columns → add
.nullable()
Examples
An update body that accepts a few fields:
app/orders/[id:int]/patch.ts
import { schemaOf } from "app/db";
import { orders } from "../orders.table";
export const schema = { body: schemaOf(orders).update.pick({ customerName: true, note: true }) };pick only the fields the client may send. A create body must not carry status, createdBy, totals or prices: the repository sets those.
Next steps
- API handlers: a handler’s
schema. - db: write the validated record to the database.
- listSchema, listOf: the schema for a list endpoint’s query.
Last updated