Skip to the code

Tag and time the cached tea catalog

Every Leaf and Kettle page that shows a tea reads it through lib/teas.ts, so those reads should be cached, and the cache must know when to let go. Write its three functions with Cache Components: start each function's body with "use cache", then call cacheTag and cacheLife from next/cache inside it.

Staff tools already revalidate by tag. Saving one tea revalidates tea:<slug>, like tea:green, and adding a tea, removing one, or importing new prices revalidates teas. So tag every entry with the list tag, teas, and with the tag of each tea in it.

getTeas() returns every tea, from db.allTeas() in @/lib/db. Tag it teas and tea:<slug> for each tea it returns, so saving any one tea refreshes the list too. The teas only change when staff change them, and those changes revalidate by tag, so use the longest built-in profile, max.

getTea(slug) returns one tea, from db.teaBySlug(slug), tagged teas and tea:<slug>, with max. When there's no such tea it returns null. A page may ask for a tea that's about to be added, so cache that answer under the same tags, but only for minutes.

getBestSellers() returns the names of this week's three best-selling teas, most sold first, from db.salesThisWeek() and db.allTeas(). It changes with every order and nothing revalidates it on demand, so give it hours and let time refresh it. Each call of each function runs exactly one cacheLife.

getTeas()         → cacheTag("teas", "tea:green", "tea:mint", …), cacheLife("max")
getTea("oolong")  → cacheTag("teas", "tea:oolong"), cacheLife("max")
getTea("matcha")  → null, cacheTag("teas", "tea:matcha"), cacheLife("minutes")
getBestSellers()  → ["Oolong tea", "Green tea", "Mint tea"], cacheLife("hours")

The app's other files

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

export type Tea = { slug: string; name: string; price: number };
 
/** The shop's teas, prices in cents: a stand-in for its database. */
export const teaRows: Tea[] = [
  { slug: "green", name: "Green tea", price: 800 },
  { slug: "mint", name: "Mint tea", price: 650 },
  { slug: "oolong", name: "Oolong tea", price: 1200 },
  { slug: "jasmine", name: "Jasmine pearls", price: 1500 },
];
 
/** Tins of each tea sold this week: it changes with every order. */
export const weeklySales: Record<string, number> = { green: 42, mint: 17, oolong: 63, jasmine: 8 };
 
export const db = {
  /** Every tea, in the catalog's order. */
  async allTeas(): Promise<Tea[]> {
    return teaRows.map((tea) => ({ ...tea }));
  },
  /** The tea with this slug, or null when there's none. */
  async teaBySlug(slug: string): Promise<Tea | null> {
    const tea = teaRows.find((row) => row.slug === slug);
    return tea ? { ...tea } : null;
  },
  /** Tins sold this week, by slug. */
  async salesThisWeek(): Promise<Record<string, number>> {
    return { ...weeklySales };
  },
};

What the tests check

  1. getTeas is tagged teas and with each tea's own tag, for max
    const teas = await getTeas();
    expect(teas.map((tea) => tea.slug)).toEqual(["green", "mint", "oolong", "jasmine"]);
    expect([...cache.tags].sort()).toEqual(["tea:green", "tea:jasmine", "tea:mint", "tea:oolong", "teas"]);
    expect(cache.lives).toEqual(["max"]);
    
  2. getTeas builds its tags from the teas it read
    teaRows.push({ slug: "sencha", name: "Sencha", price: 900 });
    await getTeas();
    expect(cache.tags).toContain("tea:sencha");
    expect(cache.tags.filter((tag) => tag.startsWith("tea:"))).toHaveLength(5);
    
  3. getTea is tagged teas and with its own tag, for max
    expect(await getTea("oolong")).toEqual({ slug: "oolong", name: "Oolong tea", price: 1200 });
    expect([...cache.tags].sort()).toEqual(["tea:oolong", "teas"]);
    expect(cache.lives).toEqual(["max"]);
    
  4. a tea that isn't there is null, cached for minutes under the same tags
    expect(await getTea("matcha")).toBe(null);
    expect([...cache.tags].sort()).toEqual(["tea:matcha", "teas"]);
    expect(cache.lives).toEqual(["minutes"]);
    
  5. best sellers are this week's top three, refreshed every hour
    expect(await getBestSellers()).toEqual(["Oolong tea", "Green tea", "Mint tea"]);
    expect(cache.lives).toEqual(["hours"]);
    
  6. every read starts its body with "use cache"
    const expectUseCache = (fn, name) => {
      if (!/\)\s*(=>\s*)?\{\s*(["'])use cache\2/.test(String(fn))) throw new Error(name + ' should start its body with "use cache", so Next.js caches what it returns');
    };
    expectUseCache(getTeas, "getTeas");
    expectUseCache(getTea, "getTea");
    expectUseCache(getBestSellers, "getBestSellers");
    

Learn more

lib/teas.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).