Skip to the code

A price change staff see at once

Staff at Leaf and Kettle change prices on a tea's admin page, /admin/teas/<slug>, in a form whose useActionState calls changePrice(previous, formData) in app/admin/actions.ts. The form sends the tea's slug and the new price in dollars, like 13.50. Write the action.

Check these in order, and return the first that fails as { error, message: null }, changing nothing: the request comes from staff, by getStaff() from @/lib/staff (Only staff can change prices.); the tea exists, by findTea(slug) from @/lib/catalog, which reads the database itself, not a cache (There's no tea with that slug.); the price, trimmed, is dollars with at most two decimals, from 0.50 to 200.00 (Enter a price from 0.50 to 200.00.). Prices are kept in cents, so 13.50 is 1350.

If the tea already has that price, return { error: null, message: "Green tea already costs $8.00." } and expire nothing. Otherwise save it with setPrice(slug, cents) and return { error: null, message: "Oolong tea now costs $13.50." }.

After saving, tell the cache. @/lib/catalog shows what each page reads: the tea's page and its admin page are cached under tea:<slug>, the catalog under teas, each collection page under collection:<name>, and the home page's Under $10 shelf under under-10. The staff member must see the new price in the page the action sends back, so expire the tea's own tag with updateTag. Shoppers' lists can show the old price for a moment while a fresh one is made, so mark them stale with revalidateTag(tag, "max"): teas, collection:<name> for each of the tea's collections, and under-10 when the old price or the new one is under $10.00.

Sam (staff) sends slug=oolong, price=9.50   (oolong was $12.00, in "roasted")
→ setPrice("oolong", 950)
→ updateTag("tea:oolong")
→ revalidateTag("teas", "max"), revalidateTag("collection:roasted", "max"), revalidateTag("under-10", "max")
→ { error: null, message: "Oolong tea now costs $9.50." }

The app's other files

lib/staff.ts, read-only. Import it as @/lib/staff.

import { cookies } from "next/headers";
 
export type Staff = { id: string; name: string };
 
/** Staff sessions: the token in the `session` cookie, and whose it is. Customers' tokens aren't here. */
const staffSessions = new Map<string, Staff>([["token-sam", { id: "s_sam", name: "Sam" }]]);
 
/** The staff member who sent this request, or null. */
export async function getStaff(): Promise<Staff | null> {
  const token = (await cookies()).get("session")?.value;
  return (token && staffSessions.get(token)) || null;
}

lib/catalog.ts, read-only. Import it as @/lib/catalog.

import { cacheLife, cacheTag } from "next/cache";
 
export type Tea = { slug: string; name: string; price: number; collections: string[] };
 
/** The shop's teas, prices in cents: a stand-in for its database. */
export const teas: Tea[] = [
  { slug: "green", name: "Green tea", price: 800, collections: ["everyday", "japanese"] },
  { slug: "oolong", name: "Oolong tea", price: 1200, collections: ["roasted"] },
  { slug: "jasmine", name: "Jasmine pearls", price: 1500, collections: [] },
];
 
/** The tea as the database has it right now, for changes: never cached. */
export async function findTea(slug: string): Promise<Tea | undefined> {
  const tea = teas.find((entry) => entry.slug === slug);
  return tea && { ...tea, collections: [...tea.collections] };
}
 
export async function setPrice(slug: string, price: number) {
  const tea = teas.find((entry) => entry.slug === slug);
  if (tea) tea.price = price;
}
 
// The cached reads behind the shop's pages, and the tags each is cached under.
 
const card = ({ slug, name, price }: Tea) => ({ slug, name, price });
 
/** The tea's page, /teas/<slug>, and its admin page, /admin/teas/<slug>. */
export async function getTea(slug: string) {
  "use cache";
  cacheTag(`tea:${slug}`);
  cacheLife("max");
  return (await findTea(slug)) ?? null;
}
 
/** The catalog, /teas. */
export async function getCatalog() {
  "use cache";
  cacheTag("teas");
  cacheLife("max");
  return teas.map(card);
}
 
/** A collection's page, /collections/<collection>. */
export async function getCollection(collection: string) {
  "use cache";
  cacheTag(`collection:${collection}`);
  cacheLife("max");
  return teas.filter((tea) => tea.collections.includes(collection)).map(card);
}
 
/** The home page's Under $10 shelf: every tea under 1000 cents. */
export async function getUnderTen() {
  "use cache";
  cacheTag("under-10");
  cacheLife("max");
  return teas.filter((tea) => tea.price < 1000).map(card);
}

What the tests check

  1. saves the price and expires the tea's own tag with updateTag
    const asStaff = (work) => withRequest({ kind: "action", cookies: { session: "token-sam" } }, work);
    const change = (fields) => changePrice({ error: null, message: null }, formData(fields));
    const priceOf = (slug) => teas.find((tea) => tea.slug === slug).price;
    const state = await asStaff(() => change({ slug: "oolong", price: "13.50" }));
    expect(state).toEqual({ error: null, message: "Oolong tea now costs $13.50." });
    expect(priceOf("oolong")).toBe(1350);
    expect(cache.updatedTags).toEqual(["tea:oolong"]);
    
  2. marks the catalog and the tea's collections stale with max, and nothing more
    const asStaff = (work) => withRequest({ kind: "action", cookies: { session: "token-sam" } }, work);
    const change = (fields) => changePrice({ error: null, message: null }, formData(fields));
    const priceOf = (slug) => teas.find((tea) => tea.slug === slug).price;
    await asStaff(() => change({ slug: "green", price: "7.50" }));
    const stale = cache.calls.filter((call) => call.name === "revalidateTag").map((call) => call.args).sort((a, b) => (a[0] < b[0] ? -1 : 1));
    expect(stale).toEqual([
      ["collection:everyday", "max"],
      ["collection:japanese", "max"],
      ["teas", "max"],
      ["under-10", "max"],
    ]);
    expect(cache.updatedTags).toEqual(["tea:green"]);
    expect(cache.revalidatedPaths).toEqual([]);
    
  3. refreshes the Under $10 shelf only when the old or the new price is under $10
    const asStaff = (work) => withRequest({ kind: "action", cookies: { session: "token-sam" } }, work);
    const change = (fields) => changePrice({ error: null, message: null }, formData(fields));
    const priceOf = (slug) => teas.find((tea) => tea.slug === slug).price;
    const lists = async (slug, price) => {
      const from = cache.calls.length;
      await asStaff(() => change({ slug, price }));
      return cache.calls.slice(from).filter((call) => call.name === "revalidateTag").map((call) => call.args[0]);
    };
    expect(await lists("jasmine", "16")).toEqual(["teas"]);
    expect(await lists("oolong", "9.50")).toContain("under-10");
    expect(await lists("green", "12")).toContain("under-10");
    expect(await lists("green", "13")).not.toContain("under-10");
    expect(await lists("oolong", "8")).toContain("under-10");
    expect(teas.map((tea) => tea.price)).toEqual([1300, 800, 1600]);
    
  4. only staff can change prices
    const asStaff = (work) => withRequest({ kind: "action", cookies: { session: "token-sam" } }, work);
    const change = (fields) => changePrice({ error: null, message: null }, formData(fields));
    const priceOf = (slug) => teas.find((tea) => tea.slug === slug).price;
    for (const cookies of [{}, { session: "token-ana" }, { session: "forged" }]) {
      const state = await withRequest({ kind: "action", cookies }, () => change({ slug: "green", price: "1" }));
      expect(state).toEqual({ error: "Only staff can change prices.", message: null });
    }
    expect(priceOf("green")).toBe(800);
    expect(cache.calls).toEqual([]);
    
  5. turns down an unknown tea or a bad price, and changes nothing
    const asStaff = (work) => withRequest({ kind: "action", cookies: { session: "token-sam" } }, work);
    const change = (fields) => changePrice({ error: null, message: null }, formData(fields));
    const priceOf = (slug) => teas.find((tea) => tea.slug === slug).price;
    expect(await asStaff(() => change({ slug: "matcha", price: "9" }))).toEqual({ error: "There's no tea with that slug.", message: null });
    for (const fields of [{ slug: "green" }, ...["", "nine", "0.49", "200.01", "7.555", "-3", "1e2", "12,50", "0x10"].map((price) => ({ slug: "green", price }))]) {
      expect(await asStaff(() => change(fields))).toEqual({ error: "Enter a price from 0.50 to 200.00.", message: null });
    }
    expect(priceOf("green")).toBe(800);
    expect(cache.calls).toEqual([]);
    expect(await asStaff(() => change({ slug: "green", price: " 0.50 " }))).toEqual({ error: null, message: "Green tea now costs $0.50." });
    expect(await asStaff(() => change({ slug: "green", price: "200" }))).toEqual({ error: null, message: "Green tea now costs $200.00." });
    
  6. an unchanged price expires nothing
    const asStaff = (work) => withRequest({ kind: "action", cookies: { session: "token-sam" } }, work);
    const change = (fields) => changePrice({ error: null, message: null }, formData(fields));
    const priceOf = (slug) => teas.find((tea) => tea.slug === slug).price;
    expect(await asStaff(() => change({ slug: "green", price: "8.00" }))).toEqual({ error: null, message: "Green tea already costs $8.00." });
    expect(await asStaff(() => change({ slug: "green", price: "8" }))).toEqual({ error: null, message: "Green tea already costs $8.00." });
    expect(cache.calls).toEqual([]);
    

Learn more

app/admin/actions.tsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).