Build a CRUD feature
≈ 20 min · you will have a full create, read, update and delete feature for orders: database table, repository, API handlers, a list page and a detail page.
CRUD is the four operations on one kind of record, such as a hardware store’s orders, a spa’s bookings. In Manh, every file of a resource lives in one folder: the folder is the path, the file name is the method.
Faster: the resource block. block_add("resource", { name: "orders", title: "Orders", fields: [...], deleteRoles: ["admin"] }) writes every file on this page (indexed table, shared enums, repository, five handlers, columns and the list page) from a field list. Each field has name, label and type: text, textarea, number, money, date, boolean or select (with options: [{ value, label, color? }]). One step is left: add the page to the menu in app/layout.tsx. Then edit the business rules in repository.ts. This page explains each file so you can read and change them.
// List: ProTable with a search form, status tabs with counts, multi-select to approve, valueEnum rendered as Badge.
// In a real app: request calls api.<resource>.list(...) and returns { data, total, success: true }.
import { useMemo, useRef, useState } from "react";
import { PageContainer, ProTable, type ActionType, type ProColumns } from "@ant-design/pro-components";
import { App, Badge, Button, Popconfirm, Space, Typography } from "antd";
import { CheckOutlined, PlusOutlined } from "@ant-design/icons";
type Status = "pending" | "approved" | "rejected";
type Row = { id: number; title: string; amount: number; owner: string; dept: string; status: Status; category: string; createdAt: string };
const STATUS = {
pending: { text: "Pending", status: "Processing" },
approved: { text: "Approved", status: "Success" },
rejected: { text: "Rejected", status: "Error" },
} as const;
const CATEGORY = { office: { text: "Office supplies" }, equipment: { text: "Equipment" }, software: { text: "Software" } };
const vnd = (n: number) => n.toLocaleString("en-US", { style: "currency", currency: "USD" });
const SEED: Row[] = [
{ id: 9, title: "Renew Microsoft 365 (12 months, 10 users)", amount: 1500, owner: "Laura Bennett", dept: "Operations", status: "pending", category: "software", createdAt: "2026-11-10" },
{ id: 8, title: "2× Dell P2423 monitors for the dev team", amount: 520, owner: "Michael Carter", dept: "Engineering", status: "pending", category: "equipment", createdAt: "2026-11-09" },
{ id: 7, title: "Letter paper (20 reams)", amount: 145, owner: "Laura Bennett", dept: "Operations", status: "approved", category: "office", createdAt: "2026-11-05" },
{ id: 6, title: "Mechanical keyboard for dev", amount: 129, owner: "Michael Carter", dept: "Engineering", status: "rejected", category: "equipment", createdAt: "2026-11-02" },
];
export default function Page() {
const { message } = App.useApp();
const ref = useRef<ActionType>(undefined);
const [rows, setRows] = useState(SEED);
const [tab, setTab] = useState<"all" | Status>("pending");
const counts = useMemo(() => ({
all: rows.length,
pending: rows.filter((r) => r.status === "pending").length,
approved: rows.filter((r) => r.status === "approved").length,
rejected: rows.filter((r) => r.status === "rejected").length,
}), [rows]);
const columns: ProColumns<Row>[] = [
{ title: "Title", dataIndex: "title", ellipsis: true, fieldProps: { placeholder: "Search by title" },
render: (_, r) => (
<Space orientation="vertical" size={0}>
<Typography.Link strong>{r.title}</Typography.Link>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>#{r.id} · {r.createdAt}</Typography.Text>
</Space>
) },
{ title: "Amount", dataIndex: "amount", align: "right", search: false, render: (_, r) => <b>{vnd(r.amount)}</b> },
{ title: "Requested by", dataIndex: "owner", search: false,
render: (_, r) => <Space orientation="vertical" size={0}><span>{r.owner}</span><Typography.Text type="secondary" style={{ fontSize: 12 }}>{r.dept}</Typography.Text></Space> },
{ title: "Status", dataIndex: "status", valueEnum: STATUS, search: false },
{ title: "Category", dataIndex: "category", valueType: "select", valueEnum: CATEGORY },
{ title: "Actions", valueType: "option", render: () => [<a key="v">View</a>] },
];
return (
<PageContainer title="All requests" subTitle="Approve or reject your team's requests">
<ProTable<Row>
actionRef={ref}
rowKey="id"
cardBordered
columns={columns}
params={{ tab, rows }}
search={{ labelWidth: "auto", searchText: "Search", resetText: "Clear filters" }}
pagination={{ pageSize: 10, showTotal: (t) => `${t} requests` }}
request={async (p: Record<string, unknown>) => {
const data = rows
.filter((r) => tab === "all" || r.status === tab)
.filter((r) => !p.title || r.title.toLowerCase().includes(String(p.title).toLowerCase()))
.filter((r) => !p.category || r.category === p.category);
return { data, total: data.length, success: true };
}}
toolbar={{
menu: {
type: "tab",
activeKey: tab,
onChange: (k) => setTab(k as typeof tab),
items: (["all", "pending", "approved", "rejected"] as const).map((k) => ({
key: k,
label: <span>{k === "all" ? "All" : STATUS[k].text}<Badge count={counts[k]} color={k === "pending" ? "orange" : "#bfbfbf"} style={{ marginInlineStart: 6 }} /></span>,
})),
},
}}
rowSelection={tab === "pending" ? {} : undefined}
tableAlertRender={({ selectedRows }) => <span><b>{selectedRows.length}</b> selected · total <b>{vnd(selectedRows.reduce((a, r) => a + r.amount, 0))}</b></span>}
tableAlertOptionRender={({ selectedRows, onCleanSelected }) => (
<Space>
<a onClick={onCleanSelected}>Clear selection</a>
<Popconfirm title={`Approve ${selectedRows.length} requests?`} onConfirm={() => {
const ids = new Set(selectedRows.map((r) => r.id));
setRows((all) => all.map((r) => (ids.has(r.id) ? { ...r, status: "approved" } : r)));
message.success(`Approved ${ids.size} requests`);
onCleanSelected();
}}>
<Button type="primary" size="small" icon={<CheckOutlined />}>Approve selected</Button>
</Popconfirm>
</Space>
)}
toolBarRender={() => [<Button key="n" type="primary" icon={<PlusOutlined />}>New request</Button>]}
/>
</PageContainer>
);
}
Build the "ProTable list" screen for my app following the Manh UI playbook (framework_docs("pro")): List: ProTable with a search form, status tabs with counts, multi-select to approve, valueEnum as Badges. Data comes from the app's API through useApiClient(); labels and fields follow my spec.File tree
You write these files. Each handler file becomes an API and a function in the generated client app/api.
app/
├── shared/order.ts order statuses + lifecycle — used by the server and the UI
└── orders/
├── orders.table.ts orders table
├── repository.ts every query + business rule
├── get.ts GET /orders → api.orders.list(params)
├── post.ts POST /orders → api.orders.create(body)
├── [id:int]/
│ ├── get.ts GET /orders/:id → api.orders.detail(id)
│ ├── patch.ts PATCH /orders/:id → api.orders.update(id, body)
│ ├── delete.ts DELETE /orders/:id → api.orders.remove(id)
│ └── page.tsx the /orders/:id page
├── orders-columns.tsx columns shared by the table and the form
└── page.tsx the /orders page.ts files run on the server, .tsx files run in the browser. Neither side imports from the other, except the app/shared folder. The UI calls the server over HTTP with useApiClient().
1. Declare the table
Each resource has one *.table.ts file. Index every column the list sorts or filters by.
import { sqliteTable, integer, text, index } from "app/db";
import { OrderStatus } from "app/shared/order";
export const orders = sqliteTable("orders", {
id: integer("id").primaryKey({ autoIncrement: true }),
customerName: text("customer_name").notNull(),
total: integer("total").notNull(), // in VND
status: text("status", { enum: OrderStatus.values }).notNull().default("pending"),
createdAt: integer("created_at").notNull(),
}, (t) => [
index("orders_created_at_idx").on(t.createdAt), // the list sorts by this
index("orders_status_idx").on(t.status), // filter by status
]);On the next deploy, manh.run creates the table in the app’s own SQLite database. You don’t write migrations.
2. Declare the statuses once
app/shared is the one folder both the server and the UI import. Write the status list there with defineEnum: labels, colours and values stay together.
import { defineEnum } from "manh/enum";
export const OrderStatus = defineEnum({
pending: ["Awaiting payment", "processing"], // [label, colour]
paid: ["Paid", "success"],
cancelled: ["Cancelled", "error"],
});
export type OrderStatus = (typeof OrderStatus.values)[number];| Property | Use in |
|---|---|
OrderStatus.values | z.enum(OrderStatus.values) in a schema, text("status", { enum }) in a table |
OrderStatus.valueEnum | ProTable and ProDescriptions columns (renders the Badge) |
OrderStatus.options | Select, Segmented |
OrderStatus.label(v), OrderStatus.color(v) | Tag, e-mails |
OrderStatus.is(v) | check whether a string is a valid status |
The order lifecycle is declared here too, with defineFlow from manh/flow: which status may move to which, and which roles may make each move. The server uses it to stop an illegal move, the UI uses it to choose the buttons to show.
import { defineFlow } from "manh/flow";
// … OrderStatus as above
export const OrderFlow = defineFlow({
pending: { paid: ["sales", "admin"], cancelled: ["sales", "admin"] }, // status → next status → roles that may do it
paid: { cancelled: ["admin"] },
cancelled: {}, // final status
});Write true instead of a role list to let any signed-in user make that move. Role names are the roles in app/auth.ts.
| Function | Use in |
|---|---|
OrderFlow.assert(user, from, to) | the server, before the write: throws 409 FLOW_ILLEGAL when the move does not exist, 403 FORBIDDEN for the wrong role |
OrderFlow.next(status, role) | the UI: the next statuses this role may move to, one button each |
OrderFlow.can(role, from, to) | check one move, returns true / false |
OrderFlow.isFinal(status) | a status with no moves left |
OrderFlow.states | array of every declared status |
Files in app/shared are .ts, with no JSX, and import only app/shared/*, manh/enum, manh/flow or manh/vn. Importing app/db or react, or using window, there makes check report shared.impure-import.
3. Write the repository
Every query and business rule lives in repository.ts. Handlers and cron jobs call the same functions, so each rule exists once.
listOf(table, query, opts) from app/db returns one page of the list with the total row count: { data, total }. You declare which columns can be searched, filtered and sorted; by default the newest record comes first.
import { fail } from "manh/errors";
import { db, eq, listOf } from "app/db";
import { OrderFlow, type OrderStatus } from "app/shared/order";
import { orders } from "./orders.table";
type User = { id: number; role: string };
export const listOrders = (query: Record<string, unknown>) =>
listOf(orders, query, {
search: [orders.customerName], // `search` → LIKE on these columns
filters: { status: orders.status }, // query key → column (equals)
sort: { createdAt: orders.createdAt, total: orders.total }, // the only columns a client may sort by
}); // { data, total }
export async function getOrder(id: number) {
const [row] = await db.select().from(orders).where(eq(orders.id, id));
if (!row) fail(404, "Order not found", "NOT_FOUND");
return row;
}
export async function createOrder(input: { customerName: string; total: number }) {
const [row] = await db.insert(orders).values({ ...input, createdAt: Date.now() }).returning();
return row;
}
export async function updateOrder(user: User, id: number, patch: Partial<{ customerName: string; total: number; status: OrderStatus }>) {
const current = await getOrder(id); // 404 when missing
if (patch.status && patch.status !== current.status) {
OrderFlow.assert(user, current.status, patch.status); // 409 FLOW_ILLEGAL / 403 FORBIDDEN
} else if (current.status === "cancelled") {
fail(409, "A cancelled order can't be edited", "CANCELLED");
}
const [row] = await db.update(orders).set(patch).where(eq(orders.id, id)).returning();
return row;
}
export async function deleteOrder(id: number) {
await getOrder(id);
await db.delete(orders).where(eq(orders.id, id));
}Business errors are thrown with fail(status, message, code) from manh/errors. The UI receives the body { error, message, code } and shows message. OrderFlow.assert throws an error with the same body shape.
For a list that needs joins, aggregates or computed columns, write Drizzle as usual; listOf is for a list over one table.
4. Write the list and create handlers
Each handler exports schema (Zod for query or body) and a default function that calls the repository. Validated input arrives in the second argument; the return value becomes JSON.
listSchema(opts) from app/db builds the schema for a list query: page (or ProTable’s current), pageSize (default 20, max 100), search, sort (only the keys you list), order (asc | desc) and the filters you add in filters.
schemaOf(orders) from app/db builds Zod schemas { insert, update } from the table’s columns. pick only the fields the client may send.
import { z } from "@hono/zod-openapi";
import { listSchema } from "app/db";
import { OrderStatus } from "app/shared/order";
import { listOrders } from "./repository";
export const schema = {
query: listSchema({
filters: { status: z.enum(OrderStatus.values).optional() },
sort: ["createdAt", "total"],
}),
};
export default (c, { query }) => listOrders(query); // { data, total }import { z } from "@hono/zod-openapi";
import { schemaOf } from "app/db";
import { orders } from "./orders.table";
import { createOrder } from "./repository";
export const schema = {
body: schemaOf(orders).insert
.pick({ customerName: true, total: true }) // the client never sends status
.extend({ total: z.number().int().positive() }),
};
export default (c, { body }) => {
c.status(201);
return createOrder(body);
};5. Write the handlers by id
The [id:int] folder gives you an id already checked as an integer. Read it as param.id and do not declare param in schema.
import { getOrder } from "../repository";
export const schema = {};
export default (c, { param }) => getOrder(param.id);import { schemaOf } from "app/db";
import { orders } from "../orders.table";
import { updateOrder } from "../repository";
export const schema = {
body: schemaOf(orders).update.pick({ customerName: true, total: true, status: true }),
};
export default (c, { user, param, body }) => updateOrder(user, param.id, body);import { deleteOrder } from "../repository";
export const access = ["admin"]; // a role declared in app/auth.ts
export const schema = {};
export default async (c, { param }) => {
await deleteOrder(param.id);
return null; // 204 No Content
};patch.ts passes user to the repository so OrderFlow.assert knows the caller’s role. When the app has app/auth.ts, every handler needs a signed-in user by default. access on delete.ts lets only the admin role delete. See Sign-in and permissions.
6. Declare the columns once
One columns array serves the table, the form and the detail page. The statuses come from app/shared/order.ts, so labels and colours match the server exactly.
import type { ProColumns } from "@ant-design/pro-components";
import type { VnValueType } from "manh/shell";
import type { OrderStatus } from "app/shared/order";
export type Order = { id: number; customerName: string; total: number; status: OrderStatus; createdAt: number };
export const orderColumns: ProColumns<Order, VnValueType>[] = [
{ title: "ID", dataIndex: "id", hideInForm: true, search: false, width: 80 },
{ title: "Customer", dataIndex: "customerName", search: false, // searched with the keyword box
formItemProps: { rules: [{ required: true }] } },
{ title: "Total", dataIndex: "total", valueType: "vnd", search: false,
formItemProps: { rules: [{ required: true }] } },
{ title: "Status", dataIndex: "status", hideInForm: true }, // changed with buttons, not the form
{ title: "Created", dataIndex: "createdAt", valueType: "dateTime", hideInForm: true, search: false },
];7. Build the list and detail pages
ResourceList from manh/shell builds the list page: status tabs with counts, a search box, paging, an Add form from the same columns, and a link from the first column to the detail page.
import { ResourceList } from "manh/shell";
import { useApiClient } from "app/api";
import { OrderStatus } from "app/shared/order";
import { orderColumns } from "./orders-columns";
export default function OrdersPage() {
const api = useApiClient();
return (
<ResourceList api={api.orders} title="Orders" path="/orders" columns={orderColumns}
status="status" statusEnum={OrderStatus} createTitle="New order" />
);
}ResourceDetail builds the detail page: title, status tag, the facts from the columns, Edit, Delete and the status buttons. The status buttons come from OrderFlow.next(status, role), so each person sees only the moves they may make.
import { ResourceDetail } from "manh/shell";
import { useApiClient } from "app/api";
import { OrderFlow, OrderStatus } from "app/shared/order";
import { orderColumns, type Order } from "../orders-columns";
export default function OrderPage() {
const api = useApiClient();
return (
<ResourceDetail<Order> api={api.orders} columns={orderColumns} path="/orders" listTitle="Orders"
title={(r) => `Order #${r.id}`} status="status" statusEnum={OrderStatus}
flow={OrderFlow} move={(to, r) => api.orders.update(r.id, { status: to })} remove />
);
}Good to know
ResourceListpassescurrent,pageSize, the filters and the keyword (assearch) to the API.listSchemaaccepts bothcurrentandpage.- Status tabs show counts when the repository calls
listOf(…, { counts: "status" }). - The modal closes when the save succeeds. On an error it stays open and shows the server’s
message. - A move to a cancelled status asks before it runs. A move that needs input, such as a cancel reason, is declared with
ask. What the user types reachesmoveas the third argument. - Add your own buttons per row with
rowActions(row, reload), and on the detail page withactions(r, reload). Each button calls the API throughuseActionfromapp/hooks. - From outside, call this API at
https://<id>.manh.run/api/orders. checkwarns when a handler callsdb.*directly (code.no-inline-drizzle-in-handler), when a list sorts by a column without an index (perf.order-unindexed), and when a hand-writtenpageSizeschema has no.max(…)(list.unbounded).
Next steps
- Call the API from the UI — function names in the generated client and error handling.
- List pages — status tabs, multi-row selection, card layout.
- Database — column types, foreign keys, schema changes on deploy.