Skip to content

Extend the Boundary Deliberately

The Course
•
35 min study

A new feature must fit the project's rules, not only its JSX. This one is an archive: archived items leave the normal list but aren't deleted. Plan on about 35 minutes in the browser. The SQLite version, with a real schema migration, is a separate optional session described at the end.

Extension workspace Next.js · 16 files
import "./globals.css"; import Link from "next/link"; export const metadata = { title: { default: "Study Library", template: "%s · Study Library" }, }; export default function Layout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library</strong> <p> Practice app: the server uses a fixed Ada actor. No real authentication is implemented. </p> <nav> <Link href="/">Items</Link> <Link href="/new">Add an item</Link> </nav> </header> {children} </body> </html> ); } import Link from "next/link"; import { Suspense } from "react"; import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; export const dynamic = "force-dynamic"; async function Count({ count }) { await new Promise((resolve) => setTimeout(resolve, 350)); return <p>{count} visible items</p>; } export default async function Page({ searchParams }) { const params = await searchParams; const raw = Array.isArray(params.q) ? params.q[0] : params.q; const q = typeof raw === "string" ? raw.trim() : ""; const rows = repository.list(currentActor(), q); return ( <main> <h1>Study Library</h1> <form action="/"> <label> Search <input name="q" defaultValue={q} /> </label> <button>Search</button> </form> <ul> {rows.map((row) => ( <li key={row.id}> <Link href={`/items/${row.id}`}>{row.title}</Link> · version{" "} {row.version} </li> ))} </ul> {!rows.length && <p>No items match.</p>} <Suspense key={q} fallback={<p>Counting…</p>}> <Count count={rows.length} /> </Suspense> </main> ); } "use server"; import { redirect } from "next/navigation"; import { revalidatePath } from "next/cache"; import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; export async function saveItem(previous, formData) { const raw = formData.get("title"); const title = typeof raw === "string" ? raw : ""; const id = Number(formData.get("id")); const version = Number(formData.get("version")); const result = id ? repository.edit(currentActor(), id, version, { title }) : repository.create(currentActor(), { title }); if (!result.ok) return { title, error: result.code === "conflict" ? "This item changed. Reload before saving." : result.code === "not_found" ? "This item is unavailable." : "Enter a title of 1–60 characters.", }; revalidatePath("/"); revalidatePath(`/items/${result.item.id}`); redirect(`/items/${result.item.id}`); } export async function removeItem(id) { const result = repository.remove(currentActor(), id); if (!result.ok) throw new Error("Item unavailable"); revalidatePath("/"); redirect("/"); } "use client"; export default function ErrorPage({ retry }) { return ( <main> <h1>Could not load this view</h1> <button onClick={() => retry()}>Try again</button> </main> ); } "use client"; import { useActionState } from "react"; import { saveItem } from "./actions.js"; export default function ItemForm({ item }) { const [state, action, pending] = useActionState(saveItem, { error: null, title: item?.title ?? "", }); return ( <form action={action}> <input type="hidden" name="id" value={item?.id ?? ""} /> <input type="hidden" name="version" value={item?.version ?? ""} /> <label> Title{" "} <input name="title" defaultValue={state.title} aria-invalid={Boolean(state.error)} aria-describedby="save-error" /> </label> <p id="save-error" role="alert"> {state.error} </p> <button disabled={pending}> {pending ? "Saving…" : item ? "Save changes" : "Add item"} </button> </form> ); } body { font: 16px/1.5 system-ui; background: #f5f8fc; color: #183048; margin: 0; } main, header { max-width: 850px; margin: auto; padding: 20px; } input, button { font: inherit; padding: 8px; margin: 4px; } a { color: #075985; } li { padding: 12px; } form { margin: 16px 0; } nav { display: flex; gap: 16px; } [role="alert"] { color: #a01818; } label { display: block; } section { padding: 12px; background: white; border-radius: 8px; } code { overflow-wrap: anywhere; } import ItemForm from "../ItemForm.jsx"; export default function NewPage() { return ( <main> <h1>Add an item</h1> <ItemForm /> </main> ); } import { repository } from "@/lib/repository.js"; export async function GET() { try { const ready = repository.probe(); return Response.json( { ready }, { status: ready ? 200 : 503, headers: { "Cache-Control": "no-store" } }, ); } catch { return Response.json({ ready: false }, { status: 503 }); } } import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; export async function GET(request) { const q = new URL(request.url).searchParams.get("q") ?? ""; return Response.json(repository.list(currentActor(), q), { headers: { "Cache-Control": "private, no-store" }, }); } export async function POST(request) { let input; try { input = await request.json(); } catch { return Response.json({ code: "invalid_json" }, { status: 400 }); } const result = repository.create(currentActor(), input); return Response.json(result, { status: result.ok ? 201 : 400 }); } import Link from "next/link"; export default function Missing() { return ( <main> <h1>Item unavailable</h1> <p>It may be missing or not visible to this caller.</p> <Link href="/">All items</Link> </main> ); } import { notFound } from "next/navigation"; import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; import ItemForm from "../../ItemForm.jsx"; import { removeItem } from "../../actions.js"; export const dynamic = "force-dynamic"; export default async function ItemPage({ params }) { const { id } = await params; const item = repository.get(currentActor(), Number(id)); if (!item) notFound(); return ( <main> <h1>{item.title}</h1> <p>Version {item.version}</p> <ItemForm item={item} /> <form action={removeItem.bind(null, item.id)}> <button>Remove item</button> </form> </main> ); } import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; export async function GET(request, { params }) { const { id } = await params; const item = repository.get(currentActor(), Number(id)); return Response.json(item ?? { code: "not_found" }, { status: item ? 200 : 404, headers: { "Cache-Control": "private, no-store" }, }); } export async function PATCH(request, { params }) { const { id } = await params; let input; try { input = await request.json(); } catch { return Response.json({ code: "invalid_json" }, { status: 400 }); } if (!input || !Number.isInteger(input.version) || input.version < 1) return Response.json({ code: "invalid_version" }, { status: 400 }); const result = repository.edit( currentActor(), Number(id), input.version, input, ); return Response.json(result, { status: result.ok ? 200 : result.code === "conflict" ? 409 : result.code === "not_found" ? 404 : 400, }); } export async function DELETE(request, { params }) { const { id } = await params; const result = repository.remove(currentActor(), Number(id)); return Response.json(result, { status: result.ok ? 200 : 404 }); } export function currentActor() { return { id: "ada", tenantId: "local" }; } export function validateDraft(input) { if (!input || typeof input.title !== "string") return { ok: false, code: "invalid_title" }; const title = input.title.trim(); if (!title || title.length > 60) return { ok: false, code: "invalid_title" }; return { ok: true, title }; } export function canWrite(actor, row) { return Boolean( actor && row && actor.tenantId === row.tenantId && actor.id === row.ownerId, ); } export function publicItem(row) { return { id: row.id, title: row.title, version: row.version }; } export const seed = [ { id: 1, title: "Read about server boundaries", ownerId: "ada", tenantId: "local", version: 1, }, { id: 2, title: "Test a stale edit", ownerId: "ada", tenantId: "local", version: 1, }, { id: 3, title: "Grace's private review", ownerId: "grace", tenantId: "local", version: 1, }, ]; import { validateDraft, canWrite, publicItem, seed } from "./domain.js"; export function createRepository(initial = seed) { let rows = initial.map((row) => ({ ...row })); let nextId = Math.max(0, ...rows.map((row) => row.id)) + 1; return { list(actor, q = "") { return rows .filter( (row) => canWrite(actor, row) && row.title.toLowerCase().includes(q.toLowerCase()), ) .map(publicItem); }, get(actor, id) { const row = rows.find((row) => row.id === id); return canWrite(actor, row) ? publicItem(row) : null; }, create(actor, input) { if (!actor) return { ok: false, code: "unauthenticated" }; const valid = validateDraft(input); if (!valid.ok) return valid; const row = { id: nextId++, title: valid.title, ownerId: actor.id, tenantId: actor.tenantId, version: 1, }; rows = [...rows, row]; return { ok: true, item: publicItem(row) }; }, edit(actor, id, version, input) { const row = rows.find((row) => row.id === id); if (!canWrite(actor, row)) return { ok: false, code: "not_found" }; if (row.version !== version) return { ok: false, code: "conflict" }; const valid = validateDraft(input); if (!valid.ok) return valid; const next = { ...row, title: valid.title, version: row.version + 1 }; rows = rows.map((item) => (item.id === id ? next : item)); return { ok: true, item: publicItem(next) }; }, remove(actor, id) { const row = rows.find((row) => row.id === id); if (!canWrite(actor, row)) return { ok: false, code: "not_found" }; rows = rows.filter((row) => row.id !== id); return { ok: true }; }, probe() { return true; }, close() {}, }; } export const repository = createRepository(); import { createRepository } from "./repository.js"; export function reviewChecks() { const make = () => createRepository(); const ada = { id: "ada", tenantId: "local" }; const search = make().list(ada, "read").length === 1; const blank = make().create(ada, { title: " " }).ok === false; const projection = !Object.hasOwn(make().get(ada, 1), "ownerId"); const repo = make(); repo.edit(ada, 1, 1, { title: "First" }); const conflict = repo.edit(ada, 1, 1, { title: "Stale" }).code === "conflict"; return [ { name: "Case-insensitive search", pass: search }, { name: "Blank draft rejected", pass: blank }, { name: "Public projection", pass: projection }, { name: "Stale edit rejected", pass: conflict }, ]; }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.

Plan before you type

Write down the answers to these first. They're the decisions the feature is made of, and each has a rule from earlier in the week:

  1. Who may archive? The same caller who may edit: canWrite (Day 4).
  2. What if the item changed since the page loaded? The same version check as edit: a stale version is a conflict, and nothing changes (Day 4).
  3. What does a successful archive change? archived becomes true and the version goes up by one, so an open edit form becomes stale.
  4. Who sees archived items? Nobody in the default list; the list includes them only when asked explicitly, with ?archived=1 (Day 1).
  5. What happens after? Invalidate the list and the item page, then redirect, in that order (Day 2).
Exercise

An archive operation

Add the feature in the browser project:

  • repository.archive(actor, id, version), returning the same results as edit: not_found, conflict, or the updated public item.
  • repository.list(actor, q, options) leaves archived items out unless options.showArchived is true.
  • An Archive item button on the item page, through a Server Action, and a Show archived link on the list.

Acceptance checks: archive Test a stale edit and see it leave the list; follow Show archived and see it marked archived at version 2. Then check the rules in your head or with a test: archiving Grace's item (id 3) gives not_found, and archiving item 2 again with version 1 gives conflict.

Your working space Next.js · 16 files
import "./globals.css"; import Link from "next/link"; export const metadata = { title: { default: "Study Library", template: "%s · Study Library" }, }; export default function Layout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library</strong> <p> Practice app: the server uses a fixed Ada actor. No real authentication is implemented. </p> <nav> <Link href="/">Items</Link> <Link href="/new">Add an item</Link> </nav> </header> {children} </body> </html> ); } import Link from "next/link"; import { Suspense } from "react"; import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; export const dynamic = "force-dynamic"; async function Count({ count }) { await new Promise((resolve) => setTimeout(resolve, 350)); return <p>{count} visible items</p>; } export default async function Page({ searchParams }) { const params = await searchParams; const raw = Array.isArray(params.q) ? params.q[0] : params.q; const q = typeof raw === "string" ? raw.trim() : ""; const rows = repository.list(currentActor(), q); return ( <main> <h1>Study Library</h1> <form action="/"> <label> Search <input name="q" defaultValue={q} /> </label> <button>Search</button> </form> <ul> {rows.map((row) => ( <li key={row.id}> <Link href={`/items/${row.id}`}>{row.title}</Link> · version{" "} {row.version} </li> ))} </ul> {!rows.length && <p>No items match.</p>} <Suspense key={q} fallback={<p>Counting…</p>}> <Count count={rows.length} /> </Suspense> </main> ); } "use server"; import { redirect } from "next/navigation"; import { revalidatePath } from "next/cache"; import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; export async function saveItem(previous, formData) { const raw = formData.get("title"); const title = typeof raw === "string" ? raw : ""; const id = Number(formData.get("id")); const version = Number(formData.get("version")); const result = id ? repository.edit(currentActor(), id, version, { title }) : repository.create(currentActor(), { title }); if (!result.ok) return { title, error: result.code === "conflict" ? "This item changed. Reload before saving." : result.code === "not_found" ? "This item is unavailable." : "Enter a title of 1–60 characters.", }; revalidatePath("/"); revalidatePath(`/items/${result.item.id}`); redirect(`/items/${result.item.id}`); } export async function removeItem(id) { const result = repository.remove(currentActor(), id); if (!result.ok) throw new Error("Item unavailable"); revalidatePath("/"); redirect("/"); } "use client"; export default function ErrorPage({ retry }) { return ( <main> <h1>Could not load this view</h1> <button onClick={() => retry()}>Try again</button> </main> ); } "use client"; import { useActionState } from "react"; import { saveItem } from "./actions.js"; export default function ItemForm({ item }) { const [state, action, pending] = useActionState(saveItem, { error: null, title: item?.title ?? "", }); return ( <form action={action}> <input type="hidden" name="id" value={item?.id ?? ""} /> <input type="hidden" name="version" value={item?.version ?? ""} /> <label> Title{" "} <input name="title" defaultValue={state.title} aria-invalid={Boolean(state.error)} aria-describedby="save-error" /> </label> <p id="save-error" role="alert"> {state.error} </p> <button disabled={pending}> {pending ? "Saving…" : item ? "Save changes" : "Add item"} </button> </form> ); } body { font: 16px/1.5 system-ui; background: #f5f8fc; color: #183048; margin: 0; } main, header { max-width: 850px; margin: auto; padding: 20px; } input, button { font: inherit; padding: 8px; margin: 4px; } a { color: #075985; } li { padding: 12px; } form { margin: 16px 0; } nav { display: flex; gap: 16px; } [role="alert"] { color: #a01818; } label { display: block; } section { padding: 12px; background: white; border-radius: 8px; } code { overflow-wrap: anywhere; } import ItemForm from "../ItemForm.jsx"; export default function NewPage() { return ( <main> <h1>Add an item</h1> <ItemForm /> </main> ); } import { repository } from "@/lib/repository.js"; export async function GET() { try { const ready = repository.probe(); return Response.json( { ready }, { status: ready ? 200 : 503, headers: { "Cache-Control": "no-store" } }, ); } catch { return Response.json({ ready: false }, { status: 503 }); } } import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; export async function GET(request) { const q = new URL(request.url).searchParams.get("q") ?? ""; return Response.json(repository.list(currentActor(), q), { headers: { "Cache-Control": "private, no-store" }, }); } export async function POST(request) { let input; try { input = await request.json(); } catch { return Response.json({ code: "invalid_json" }, { status: 400 }); } const result = repository.create(currentActor(), input); return Response.json(result, { status: result.ok ? 201 : 400 }); } import Link from "next/link"; export default function Missing() { return ( <main> <h1>Item unavailable</h1> <p>It may be missing or not visible to this caller.</p> <Link href="/">All items</Link> </main> ); } import { notFound } from "next/navigation"; import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; import ItemForm from "../../ItemForm.jsx"; import { removeItem } from "../../actions.js"; export const dynamic = "force-dynamic"; export default async function ItemPage({ params }) { const { id } = await params; const item = repository.get(currentActor(), Number(id)); if (!item) notFound(); return ( <main> <h1>{item.title}</h1> <p>Version {item.version}</p> <ItemForm item={item} /> <form action={removeItem.bind(null, item.id)}> <button>Remove item</button> </form> </main> ); } import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; export async function GET(request, { params }) { const { id } = await params; const item = repository.get(currentActor(), Number(id)); return Response.json(item ?? { code: "not_found" }, { status: item ? 200 : 404, headers: { "Cache-Control": "private, no-store" }, }); } export async function PATCH(request, { params }) { const { id } = await params; let input; try { input = await request.json(); } catch { return Response.json({ code: "invalid_json" }, { status: 400 }); } if (!input || !Number.isInteger(input.version) || input.version < 1) return Response.json({ code: "invalid_version" }, { status: 400 }); const result = repository.edit( currentActor(), Number(id), input.version, input, ); return Response.json(result, { status: result.ok ? 200 : result.code === "conflict" ? 409 : result.code === "not_found" ? 404 : 400, }); } export async function DELETE(request, { params }) { const { id } = await params; const result = repository.remove(currentActor(), Number(id)); return Response.json(result, { status: result.ok ? 200 : 404 }); } export function currentActor() { return { id: "ada", tenantId: "local" }; } export function validateDraft(input) { if (!input || typeof input.title !== "string") return { ok: false, code: "invalid_title" }; const title = input.title.trim(); if (!title || title.length > 60) return { ok: false, code: "invalid_title" }; return { ok: true, title }; } export function canWrite(actor, row) { return Boolean( actor && row && actor.tenantId === row.tenantId && actor.id === row.ownerId, ); } export function publicItem(row) { return { id: row.id, title: row.title, version: row.version }; } export const seed = [ { id: 1, title: "Read about server boundaries", ownerId: "ada", tenantId: "local", version: 1, }, { id: 2, title: "Test a stale edit", ownerId: "ada", tenantId: "local", version: 1, }, { id: 3, title: "Grace's private review", ownerId: "grace", tenantId: "local", version: 1, }, ]; import { validateDraft, canWrite, publicItem, seed } from "./domain.js"; export function createRepository(initial = seed) { let rows = initial.map((row) => ({ ...row })); let nextId = Math.max(0, ...rows.map((row) => row.id)) + 1; return { list(actor, q = "") { return rows .filter( (row) => canWrite(actor, row) && row.title.toLowerCase().includes(q.toLowerCase()), ) .map(publicItem); }, get(actor, id) { const row = rows.find((row) => row.id === id); return canWrite(actor, row) ? publicItem(row) : null; }, create(actor, input) { if (!actor) return { ok: false, code: "unauthenticated" }; const valid = validateDraft(input); if (!valid.ok) return valid; const row = { id: nextId++, title: valid.title, ownerId: actor.id, tenantId: actor.tenantId, version: 1, }; rows = [...rows, row]; return { ok: true, item: publicItem(row) }; }, edit(actor, id, version, input) { const row = rows.find((row) => row.id === id); if (!canWrite(actor, row)) return { ok: false, code: "not_found" }; if (row.version !== version) return { ok: false, code: "conflict" }; const valid = validateDraft(input); if (!valid.ok) return valid; const next = { ...row, title: valid.title, version: row.version + 1 }; rows = rows.map((item) => (item.id === id ? next : item)); return { ok: true, item: publicItem(next) }; }, remove(actor, id) { const row = rows.find((row) => row.id === id); if (!canWrite(actor, row)) return { ok: false, code: "not_found" }; rows = rows.filter((row) => row.id !== id); return { ok: true }; }, probe() { return true; }, close() {}, }; } export const repository = createRepository(); import { createRepository } from "./repository.js"; export function reviewChecks() { const make = () => createRepository(); const ada = { id: "ada", tenantId: "local" }; const search = make().list(ada, "read").length === 1; const blank = make().create(ada, { title: " " }).ok === false; const projection = !Object.hasOwn(make().get(ada, 1), "ownerId"); const repo = make(); repo.edit(ada, 1, 1, { title: "First" }); const conflict = repo.edit(ada, 1, 1, { title: "Stale" }).code === "conflict"; return [ { name: "Case-insensitive search", pass: search }, { name: "Blank draft rejected", pass: blank }, { name: "Public projection", pass: projection }, { name: "Stale edit rejected", pass: conflict }, ]; }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

archive is edit with a different change. Its guards, in their order, are the same two lines; only the row it builds differs. The list filter is a separate decision from the write guard.

Hint 2: a first step

Copy edit into a new archive(actor, id, version) method, delete the draft validation, and build next with archived: true instead of a new title. Then call it from a new archiveItem(id, version) action, bound on the item page like Remove item. Leave the list until the button works.

One implementation
Archive: one implementation Next.js · 16 files
import "./globals.css"; import Link from "next/link"; export const metadata = { title: { default: "Study Library", template: "%s · Study Library" }, }; export default function Layout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library</strong> <p> Practice app: the server uses a fixed Ada actor. No real authentication is implemented. </p> <nav> <Link href="/">Items</Link> <Link href="/new">Add an item</Link> </nav> </header> {children} </body> </html> ); } import Link from "next/link"; import { Suspense } from "react"; import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; export const dynamic = "force-dynamic"; async function Count({ count }) { await new Promise((resolve) => setTimeout(resolve, 350)); return <p>{count} visible items</p>; } export default async function Page({ searchParams }) { const params = await searchParams; const raw = Array.isArray(params.q) ? params.q[0] : params.q; const q = typeof raw === "string" ? raw.trim() : ""; const showArchived = params.archived === "1"; const rows = repository.list(currentActor(), q, { showArchived }); return ( <main> <h1>Study Library</h1> <form action="/"> <label> Search <input name="q" defaultValue={q} /> </label> <button>Search</button> </form> <p> {showArchived ? ( <Link href="/">Hide archived</Link> ) : ( <Link href="/?archived=1">Show archived</Link> )} </p> <ul> {rows.map((row) => ( <li key={row.id}> <Link href={`/items/${row.id}`}>{row.title}</Link> · version{" "} {row.version} {row.archived && " · archived"} </li> ))} </ul> {!rows.length && <p>No items match.</p>} <Suspense key={q} fallback={<p>Counting…</p>}> <Count count={rows.length} /> </Suspense> </main> ); } "use server"; import { redirect } from "next/navigation"; import { revalidatePath } from "next/cache"; import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; export async function saveItem(previous, formData) { const raw = formData.get("title"); const title = typeof raw === "string" ? raw : ""; const id = Number(formData.get("id")); const version = Number(formData.get("version")); const result = id ? repository.edit(currentActor(), id, version, { title }) : repository.create(currentActor(), { title }); if (!result.ok) return { title, error: result.code === "conflict" ? "This item changed. Reload before saving." : result.code === "not_found" ? "This item is unavailable." : "Enter a title of 1–60 characters.", }; revalidatePath("/"); revalidatePath(`/items/${result.item.id}`); redirect(`/items/${result.item.id}`); } export async function removeItem(id) { const result = repository.remove(currentActor(), id); if (!result.ok) throw new Error("Item unavailable"); revalidatePath("/"); redirect("/"); } export async function archiveItem(id, version) { const result = repository.archive(currentActor(), id, version); if (!result.ok) throw new Error( result.code === "conflict" ? "This item changed. Reload first." : "Item unavailable", ); revalidatePath("/"); revalidatePath(`/items/${id}`); redirect("/"); } "use client"; export default function ErrorPage({ retry }) { return ( <main> <h1>Could not load this view</h1> <button onClick={() => retry()}>Try again</button> </main> ); } "use client"; import { useActionState } from "react"; import { saveItem } from "./actions.js"; export default function ItemForm({ item }) { const [state, action, pending] = useActionState(saveItem, { error: null, title: item?.title ?? "", }); return ( <form action={action}> <input type="hidden" name="id" value={item?.id ?? ""} /> <input type="hidden" name="version" value={item?.version ?? ""} /> <label> Title{" "} <input name="title" defaultValue={state.title} aria-invalid={Boolean(state.error)} aria-describedby="save-error" /> </label> <p id="save-error" role="alert"> {state.error} </p> <button disabled={pending}> {pending ? "Saving…" : item ? "Save changes" : "Add item"} </button> </form> ); } body { font: 16px/1.5 system-ui; background: #f5f8fc; color: #183048; margin: 0; } main, header { max-width: 850px; margin: auto; padding: 20px; } input, button { font: inherit; padding: 8px; margin: 4px; } a { color: #075985; } li { padding: 12px; } form { margin: 16px 0; } nav { display: flex; gap: 16px; } [role="alert"] { color: #a01818; } label { display: block; } section { padding: 12px; background: white; border-radius: 8px; } code { overflow-wrap: anywhere; } import ItemForm from "../ItemForm.jsx"; export default function NewPage() { return ( <main> <h1>Add an item</h1> <ItemForm /> </main> ); } import { repository } from "@/lib/repository.js"; export async function GET() { try { const ready = repository.probe(); return Response.json( { ready }, { status: ready ? 200 : 503, headers: { "Cache-Control": "no-store" } }, ); } catch { return Response.json({ ready: false }, { status: 503 }); } } import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; export async function GET(request) { const q = new URL(request.url).searchParams.get("q") ?? ""; return Response.json(repository.list(currentActor(), q), { headers: { "Cache-Control": "private, no-store" }, }); } export async function POST(request) { let input; try { input = await request.json(); } catch { return Response.json({ code: "invalid_json" }, { status: 400 }); } const result = repository.create(currentActor(), input); return Response.json(result, { status: result.ok ? 201 : 400 }); } import Link from "next/link"; export default function Missing() { return ( <main> <h1>Item unavailable</h1> <p>It may be missing or not visible to this caller.</p> <Link href="/">All items</Link> </main> ); } import { notFound } from "next/navigation"; import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; import ItemForm from "../../ItemForm.jsx"; import { archiveItem, removeItem } from "../../actions.js"; export const dynamic = "force-dynamic"; export default async function ItemPage({ params }) { const { id } = await params; const item = repository.get(currentActor(), Number(id)); if (!item) notFound(); return ( <main> <h1>{item.title}</h1> <p> Version {item.version} {item.archived && " · archived"} </p> <ItemForm item={item} /> {!item.archived && ( <form action={archiveItem.bind(null, item.id, item.version)}> <button>Archive item</button> </form> )} <form action={removeItem.bind(null, item.id)}> <button>Remove item</button> </form> </main> ); } import { repository } from "@/lib/repository.js"; import { currentActor } from "@/lib/actor.js"; export async function GET(request, { params }) { const { id } = await params; const item = repository.get(currentActor(), Number(id)); return Response.json(item ?? { code: "not_found" }, { status: item ? 200 : 404, headers: { "Cache-Control": "private, no-store" }, }); } export async function PATCH(request, { params }) { const { id } = await params; let input; try { input = await request.json(); } catch { return Response.json({ code: "invalid_json" }, { status: 400 }); } if (!input || !Number.isInteger(input.version) || input.version < 1) return Response.json({ code: "invalid_version" }, { status: 400 }); const result = repository.edit( currentActor(), Number(id), input.version, input, ); return Response.json(result, { status: result.ok ? 200 : result.code === "conflict" ? 409 : result.code === "not_found" ? 404 : 400, }); } export async function DELETE(request, { params }) { const { id } = await params; const result = repository.remove(currentActor(), Number(id)); return Response.json(result, { status: result.ok ? 200 : 404 }); } export function currentActor() { return { id: "ada", tenantId: "local" }; } export function validateDraft(input) { if (!input || typeof input.title !== "string") return { ok: false, code: "invalid_title" }; const title = input.title.trim(); if (!title || title.length > 60) return { ok: false, code: "invalid_title" }; return { ok: true, title }; } export function canWrite(actor, row) { return Boolean( actor && row && actor.tenantId === row.tenantId && actor.id === row.ownerId, ); } export function publicItem(row) { return { id: row.id, title: row.title, version: row.version, archived: row.archived === true, }; } export const seed = [ { id: 1, title: "Read about server boundaries", ownerId: "ada", tenantId: "local", version: 1, }, { id: 2, title: "Test a stale edit", ownerId: "ada", tenantId: "local", version: 1, }, { id: 3, title: "Grace's private review", ownerId: "grace", tenantId: "local", version: 1, }, ]; import { validateDraft, canWrite, publicItem, seed } from "./domain.js"; export function createRepository(initial = seed) { let rows = initial.map((row) => ({ ...row })); let nextId = Math.max(0, ...rows.map((row) => row.id)) + 1; return { list(actor, q = "", { showArchived = false } = {}) { return rows .filter( (row) => canWrite(actor, row) && (showArchived || !row.archived) && row.title.toLowerCase().includes(q.toLowerCase()), ) .map(publicItem); }, get(actor, id) { const row = rows.find((row) => row.id === id); return canWrite(actor, row) ? publicItem(row) : null; }, create(actor, input) { if (!actor) return { ok: false, code: "unauthenticated" }; const valid = validateDraft(input); if (!valid.ok) return valid; const row = { id: nextId++, title: valid.title, ownerId: actor.id, tenantId: actor.tenantId, version: 1, }; rows = [...rows, row]; return { ok: true, item: publicItem(row) }; }, edit(actor, id, version, input) { const row = rows.find((row) => row.id === id); if (!canWrite(actor, row)) return { ok: false, code: "not_found" }; if (row.version !== version) return { ok: false, code: "conflict" }; const valid = validateDraft(input); if (!valid.ok) return valid; const next = { ...row, title: valid.title, version: row.version + 1 }; rows = rows.map((item) => (item.id === id ? next : item)); return { ok: true, item: publicItem(next) }; }, archive(actor, id, version) { const row = rows.find((row) => row.id === id); if (!canWrite(actor, row)) return { ok: false, code: "not_found" }; if (row.version !== version) return { ok: false, code: "conflict" }; const next = { ...row, archived: true, version: row.version + 1 }; rows = rows.map((item) => (item.id === id ? next : item)); return { ok: true, item: publicItem(next) }; }, remove(actor, id) { const row = rows.find((row) => row.id === id); if (!canWrite(actor, row)) return { ok: false, code: "not_found" }; rows = rows.filter((row) => row.id !== id); return { ok: true }; }, probe() { return true; }, close() {}, }; } export const repository = createRepository(); import { createRepository } from "./repository.js"; export function reviewChecks() { const make = () => createRepository(); const ada = { id: "ada", tenantId: "local" }; const search = make().list(ada, "read").length === 1; const blank = make().create(ada, { title: " " }).ok === false; const projection = !Object.hasOwn(make().get(ada, 1), "ownerId"); const repo = make(); repo.edit(ada, 1, 1, { title: "First" }); const conflict = repo.edit(ada, 1, 1, { title: "Stale" }).code === "conflict"; return [ { name: "Case-insensitive search", pass: search }, { name: "Blank draft rejected", pass: blank }, { name: "Public projection", pass: projection }, { name: "Stale edit rejected", pass: conflict }, ]; }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.

The repository method keeps edit's guards in the same order, so another owner's item is not_found before its version is even looked at:

JavaScript
archive(actor, id, version) {
  const row = rows.find((row) => row.id === id);
  if (!canWrite(actor, row)) return { ok: false, code: "not_found" };
  if (row.version !== version) return { ok: false, code: "conflict" };
  const next = { ...row, archived: true, version: row.version + 1 };
  rows = rows.map((item) => (item.id === id ? next : item));
  return { ok: true, item: publicItem(next) };
},

list gains (showArchived || !row.archived) inside the scoped filter, so the owner check still runs first. publicItem adds archived because the page shows it. The action binds both the id and the version the page rendered, so archiving from a stale page is a conflict rather than a silent overwrite, and it revalidates before redirecting. Compare each choice with yours; a different shape that keeps the five decisions above is just as right.

Going further: the database version

In the downloaded SQLite project the same feature needs a schema change. Do it as its own session of about an hour:

  1. The project tracks its schema with PRAGMA user_version (it's 1 now). Add a step to version 2 that runs ALTER TABLE items ADD COLUMN archived INTEGER NOT NULL DEFAULT 0, and a test that creates a version-1 database, opens it with the new code, and checks every title and version survived.
  2. Copy edit's conditional UPDATE, which already matches id, ownerId, tenantId and version in one statement, and set archived=1 instead of the title. As in edit, "no row changed" means not_found or conflict.
  3. Run npm test and the project's checks from the previous lesson.

Editing the seed data instead of migrating only works on an empty database; real users' data would never get the column.

Was this article helpful?

Your response is saved on this device.