The table, port, adapter, router and view a new feature adds to the stack, generated live.
A feature is a table, a port, an adapter, a router and a view, and each one is a file in the stack. Adding one means adding each file in turn, in the order below. The todo feature is the worked example: the figure generates it in the preset you pick, and the lines that belong to it are marked.
Two rules
Add a port only when two implementations warrant it
A second ORM, a second API style or a second storage provider is what warrants a port. The builder writes one for each feature because it offers two adapters for it, Drizzle and Prisma; with one implementation, a port is only a layer to read through.
Switching an adapter never edits a page or a router
Switching the ORM rewrites the table, the adapter and the migrations. The view and the feature router keep their code, because they only ever see the port.
Table
The feature's table, in the schema the ORM reads. With Drizzle it is a file of its own and one line in the schema index that exports it.
packages/db/src/schema/todo.ts
12345678import{ integer, sqliteTable, text }from"drizzle-orm/sqlite-core";import{ idColumn }from"../columns";exportconst todo =sqliteTable("todo",{ id:idColumn(), text:text("text").notNull(), done:integer("done",{ mode:"boolean"}).notNull().default(false),});
packages/db/src/schema/index.ts
123/* Every table, one file per area. drizzle-kit and the client read this folder through here. */export*from"./auth";export*from"./todo";
Port
The names the calls need from storage, in plain words: the row type and the repo interface. No ORM is named in it.
packages/api/src/ports.ts
123456789101112131415/** The domain and its ports: what the calls need from storage, in plain words. No ORM is named here. */exporttypeTodo={ id:number; text:string; done:boolean};/** What the todo calls need from storage. The adapter for each ORM implements it in db/repos. */exportinterfaceTodoRepo{list():Promise<Todo[]>;add(text:string):Promise<Todo>;toggle(id:number, done:boolean):Promise<Todo>;}/** Every repository the API calls, by feature. */exporttypeRepos={ todo:TodoRepo;};
Adapter
The ORM's side of the port, wired into the repos. Only this file knows the ORM.
packages/db/src/repos.ts
1234567891011121314151617181920212223242526import{ eq }from"drizzle-orm";import{ todo }from"./schema";importtype{ db as client }from"./client";typeDb=typeof client;/** The row a write returned; a write that returns none did not happen. */function first<T>(rows:readonlyT[]):T{const[row]= rows;if(row ===undefined)thrownewError("The write returned no row");return row;}const todoRepo =(db:Db)=>({ list:async()=> db.select().from(todo), add:async(text:string)=>first(await db.insert(todo).values({ text }).returning()), toggle:async(id:number, done:boolean)=>first(await db.update(todo).set({ done }).where(eq(todo.id, id)).returning()),});/** The registry: wires each port to the adapter the chosen ORM writes for it. */exportfunctioncreateRepos(db:Db){return{ todo:todoRepo(db),};}
Feature router
The feature's calls, built from the shared procedures and the port. A call names its access and nothing else.
packages/api/src/routers/todo.ts
1234567891011121314151617181920212223import*as z from"zod";import{ base }from"../procedures";/** What each call takes. */exportconst addTodoInput = z.object({ text: z.string().min(1)});exportconst toggleTodoInput = z.object({ id: z.number(), done: z.boolean()});exportconst listTodos = base.handler(({ context })=> context.repos.todo.list());exportconst addTodo = base.input(addTodoInput).handler(({ context, input })=> context.repos.todo.add(input.text));exportconst toggleTodo = base.input(toggleTodoInput).handler(({ context, input })=> context.repos.todo.toggle(input.id, input.done));/** The feature as the client reads it: api.todo.list and the rest. */exportconst todoRouter ={ list: listTodos, add: addTodo, toggle: toggleTodo,};
Root router
One line joins the feature to the whole API, so the client reads it as api.todo.
packages/api/src/router.ts
12345678910import{ base }from"./procedures";import{ todoRouter }from"./routers/todo";/** The whole API. A feature joins by adding its router here. */exportconst router ={ health: base.handler(()=>"ok"), todo: todoRouter,};exporttypeRouter=typeof router;
View
The page that uses the feature. It calls the API through the client and never imports the port, the adapter or the ORM.
apps/web/src/client/components/todo-list.tsx
12345678910111213141516171819202122232425262728293031323334353637383940414243444546import{ useMutation, useQuery, useQueryClient }from"@tanstack/react-query";import{ useState }from"react";import{ api }from"@/client/lib/api";/** Reads and writes through `api`: the same lines whichever API, framework or ORM is behind it. */exportfunctionTodoList(){const queryClient =useQueryClient();const refresh ={ onSuccess:()=> queryClient.invalidateQueries({ queryKey: api.todo.key()}),};const todos =useQuery(api.todo.list.queryOptions());const add =useMutation(api.todo.add.mutationOptions(refresh));const toggle =useMutation(api.todo.toggle.mutationOptions(refresh));const[text, setText]=useState("");return(<section><formonSubmit={(event)=>{ event.preventDefault(); add.mutate({ text });setText("");}}><inputvalue={text}onChange={(event)=>setText(event.target.value)}placeholder="Add a todo"/><buttontype="submit"disabled={!text}> Add</button></form><ul>{todos.data?.map((todo)=>(<likey={todo.id}><label><inputtype="checkbox"checked={todo.done}onChange={()=> toggle.mutate({ id: todo.id, done:!todo.done})}/>{todo.text}</label></li>))}</ul></section>);}