Skip to Content

repository.ts

repository.ts holds every database call and business rule of one resource, so handlers, cron jobs and mail handlers all call one place.

app/orders/ ├── orders.table.ts ├── repository.ts # listOrders, getOrder, createOrder, moveOrder… ├── get.ts # calls listOrders ├── post.ts # calls createOrder └── remind.cron.ts # calls the same repository

What it does

An order has statuses, only some roles may move it, the server computes the total, stock must not go negative. All of that lives in repository.ts. A handler only validates input, calls one function and returns the result.

A broken rule throws with fail(status, message, code). Handlers need no try/catch; the UI gets { message, code } to show.

Exports

Any functions. The file name is always repository.ts, inside the resource’s folder.

Example

app/orders/repository.ts
import { db, eq, sql, listOf } from "app/db"; import { fail } from "manh/errors"; import { orders } from "./orders.table"; import { products } from "../products/products.table"; type Actor = { id: number; role: string }; export const listOrders = (user: Actor, query) => listOf(orders, query, { search: [orders.customerName], filters: { status: orders.status }, sort: { createdAt: orders.createdAt }, where: user.role === "sales" ? eq(orders.createdBy, user.id) : undefined, // sales see only their own orders }); export async function createOrder(user: Actor, input: { productId: number; quantity: number; customerName: string }) { const [p] = await db.select().from(products).where(eq(products.id, input.productId)); if (!p) fail(404, "Product not found", "NOT_FOUND"); if (p.stock < input.quantity) fail(409, `Only ${p.stock} left`, "OUT_OF_STOCK"); await db.update(products).set({ stock: sql`${products.stock} - ${input.quantity}` }).where(eq(products.id, p.id)); const [row] = await db.insert(orders).values({ ...input, total: p.price * input.quantity, status: "new", createdBy: user.id, createdAt: Date.now(), }).returning(); return row; }

Good to know

  • Requests to one app run one at a time, so a read-then-write (check stock, then decrement) can’t be interleaved. The exception is an await on outside I/O (fetch, sending mail, calling AI), which lets other requests in. Send mail after the writes.
  • Never call db.transaction(async …). Check everything before the first write; for several writes that must all succeed or all fail, use a synchronous callback with no await.
  • At most 100 bound values per statement. A multi-row insert is split for you in one transaction (or use insertMany); replace inArray with 100+ ids by a join or subquery.
  • Don’t let the client send status, createdBy, prices or totals. The repository sets them.
  • Status moves follow a lifecycle declared once with defineFlow in shared/: call OrderFlow.assert(user, row.status, to) before the write.

Next steps

  • Build a CRUD feature — put table, repository, handlers and pages together for one resource.
  • shared/ — declare the status lifecycle with defineFlow for the repository to enforce.
  • Database — listOf, transactions and statement limits.
Last updated