Skip to content

On Your Own: An Activity Feed

The Course
•
30 min study

This is a fresh brief that combines Days 3 to 6, not another copy of the Review Queue. Sketch the decisions before you write code. Plan on about 30 minutes for a first attempt at the acceptance cases; finish them, and the last section, in another sitting if you need to.

The brief

Reviewers want an activity feed: GET /api/activity?after=3&limit=2. Write the rule as run({ actor, rows, query }), where query holds the raw query strings (or undefined when a parameter is absent), and return everything the route handler needs to answer: status, body, cacheControl and a log event.

  1. Who (Day 1). An actor without a non-empty tenantId gets 401 with code unauthenticated. Only rows in the actor's tenant appear.
  2. Which page (Day 3). limit defaults to 10 and must be a whole number from 1 to 50; after defaults to 0 and must be a whole number. Anything else is 400 with invalid_limit or invalid_cursor, checked in that order. Page by id with one extra row, so nextCursor is the last id shown when more rows exist, and null when they don't.
  3. What leaves (Days 1 and 3). Items carry id and title only. An error body is exactly { code }.
  4. Who may cache it (Day 5). A page is per-tenant data, so cacheControl is "private, no-store". A rejection is "no-store".
  5. What's logged (Day 6). A page logs { name: "activity_page", count, hasMore }; a rejection logs { name: "activity_rejected", code }. Never titles or tenant ids: the log is read by more people than the feed.

Keep run deterministic and leave its input unchanged.

Acceptance cases

The workspace's examples hold four rows of activity, one from another tenant, and these four cases:

  • Ada's tenant, limit: "2": items 1 and 3, nextCursor: 3, hasMore: true.
  • The same with after: "3": item 4 only, nextCursor: null.
  • limit: "0": 400 invalid_limit, logged as a rejection.
  • No actor: 401 unauthenticated.
Your working space Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Independent workspace</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ actor, rows, query }) { // Implement GET /api/activity from the brief. return null; } const rows = [ { id: 1, tenantId: "a", title: "Ada approved 1" }, { id: 2, tenantId: "b", title: "Other tenant" }, { id: 3, tenantId: "a", title: "Grace edited 3" }, { id: 4, tenantId: "a", title: "Ada archived 4" }, ]; export const examples = [ [ { actor: { tenantId: "a" }, rows, query: { limit: "2" } }, { status: 200, body: { items: [ { id: 1, title: "Ada approved 1" }, { id: 3, title: "Grace edited 3" }, ], nextCursor: 3, }, cacheControl: "private, no-store", event: { name: "activity_page", count: 2, hasMore: true }, }, ], [ { actor: { tenantId: "a" }, rows, query: { after: "3", limit: "2" } }, { status: 200, body: { items: [{ id: 4, title: "Ada archived 4" }], nextCursor: null }, cacheControl: "private, no-store", event: { name: "activity_page", count: 1, hasMore: false }, }, ], [ { actor: { tenantId: "a" }, rows, query: { limit: "0" } }, { status: 400, body: { code: "invalid_limit" }, cacheControl: "no-store", event: { name: "activity_rejected", code: "invalid_limit" }, }, ], [ { actor: null, rows, query: {} }, { status: 401, body: { code: "unauthenticated" }, cacheControl: "no-store", event: { name: "activity_rejected", code: "unauthenticated" }, }, ], ];
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.

Before writing run, add at least two cases of your own to examples: the least convenient inputs you can find, such as limit: "1.5", after: "x", or a cursor past the last row. Work out their results first.

Hint 1: the idea

Decide in order: is there an actor, are the inputs valid, which rows, which fields. Every early answer is a rejection with its own code; only the end of the function builds a page. One small reject(code) helper keeps all the rejections the same shape.

Hint 2: a first step

Write a helper that turns a raw query string into a whole number: undefined gives the default, a string of digits gives its number, anything else gives NaN. Then !(limit >= 1 && limit <= 50) rejects NaN as well.

Show one solution
One solution Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>One independent solution</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } // Query values arrive as strings, or undefined when absent. function whole(value, fallback) { if (value === undefined) return fallback; return /^\d+$/.test(value) ? Number(value) : NaN; } function reject(code) { return { status: code === "unauthenticated" ? 401 : 400, body: { code }, cacheControl: "no-store", event: { name: "activity_rejected", code }, }; } export function run({ actor, rows, query }) { if (typeof actor?.tenantId !== "string" || !actor.tenantId) return reject("unauthenticated"); const limit = whole(query.limit, 10); if (!(limit >= 1 && limit <= 50)) return reject("invalid_limit"); const after = whole(query.after, 0); if (Number.isNaN(after)) return reject("invalid_cursor"); const window = rows .filter((row) => row.tenantId === actor.tenantId && row.id > after) .toSorted((a, b) => a.id - b.id) .slice(0, limit + 1); const items = window.slice(0, limit).map(({ id, title }) => ({ id, title })); const hasMore = window.length > limit; return { status: 200, body: { items, nextCursor: hasMore ? items.at(-1).id : null }, cacheControl: "private, no-store", event: { name: "activity_page", count: items.length, hasMore }, }; } const rows = [ { id: 1, tenantId: "a", title: "Ada approved 1" }, { id: 2, tenantId: "b", title: "Other tenant" }, { id: 3, tenantId: "a", title: "Grace edited 3" }, { id: 4, tenantId: "a", title: "Ada archived 4" }, ]; export const examples = [ [ { actor: { tenantId: "a" }, rows, query: { limit: "2" } }, { status: 200, body: { items: [ { id: 1, title: "Ada approved 1" }, { id: 3, title: "Grace edited 3" }, ], nextCursor: 3, }, cacheControl: "private, no-store", event: { name: "activity_page", count: 2, hasMore: true }, }, ], [ { actor: { tenantId: "a" }, rows, query: { after: "3", limit: "2" } }, { status: 200, body: { items: [{ id: 4, title: "Ada archived 4" }], nextCursor: null }, cacheControl: "private, no-store", event: { name: "activity_page", count: 1, hasMore: false }, }, ], [ { actor: { tenantId: "a" }, rows, query: { limit: "0" } }, { status: 400, body: { code: "invalid_limit" }, cacheControl: "no-store", event: { name: "activity_rejected", code: "invalid_limit" }, }, ], [ { actor: null, rows, query: {} }, { status: 401, body: { code: "unauthenticated" }, cacheControl: "no-store", event: { name: "activity_rejected", code: "unauthenticated" }, }, ], ];
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.

/^\d+$/ accepts only digits, so "1.5", "-1", "1e3" and "" are all invalid, where Number() alone would accept some of them. The page uses limit + 1 rows to learn hasMore without a second query. The items and the event are built from allowlists, so a new column in rows can't leak into either.

The route handler around it is short, because every decision is in run:

JavaScript
export async function GET(request) {
  const params = new URL(request.url).searchParams;
  const query = {
    after: params.get("after") ?? undefined,
    limit: params.get("limit") ?? undefined,
  };
  const result = run({ actor: await currentActor(), rows: await loadActivity(), query });
  console.log(JSON.stringify(result.event));
  return Response.json(result.body, {
    status: result.status,
    headers: { "Cache-Control": result.cacheControl },
  });
}

loadActivity() stands for the database query. In a real project, the tenant filter, the id > after condition and the LIMIT belong in that SQL, with an index on (tenantId, id), rather than loading every row and filtering in JavaScript.

Continue independently

Add an optional type filter (approved, edited, archived) as an allowlist: an unknown type is 400 invalid_type. Then explain what a cursor from a filtered page means if the client changes the filter, and what your route should do about it.

Was this article helpful?

Your response is saved on this device.