Leaf and Kettle runs flash sales: for a few hours, a tea costs less. Every page that shows a price reads it through getPrice(slug) in lib/prices.ts, a cached function. Write it.
Start its body with "use cache" and tag it price:<slug>: staff tools revalidate that tag when they start a sale or stop one early. Read the tea with findTea(slug) and its sale with findSale(slug) from @/lib/catalog, prices in cents. Return null for a tea the shop doesn't sell, and { amount, onSale } for one it does. Call cacheLife exactly once each time.
When no sale is running for the tea (there's none, or its endsAt is not after Date.now()), return the regular price with onSale: false and cacheLife("max"): regular prices only change when staff change them, and then staff revalidate the tag. A tea the shop doesn't sell gets max too.
While a sale is running, return its price with onSale: true, and choose the lifetime yourself: an object with all three of stale, revalidate, and expire, in seconds. Here's what each does. The server hands out its copy until the copy is expire seconds old, and for requests after revalidate seconds it makes a fresh one in the background. The browser's router then reuses what it got for stale seconds, and never for less than 30, whatever stale says.
The lifetime must keep four promises. A shopper never sees a sale price more than 60 seconds old: max(stale, 30) + expire is at most 60. No server copy outlives the sale: expire is at most the seconds left until endsAt. Next.js accepts it: revalidate is no more than expire, since Next.js throws when it is, and above 0 unless expire is 0. And it caches as long as that allows: expire is the smaller of what's left of the 60 seconds after the browser's share, and the whole seconds left in the sale, rounded down.
Oolong costs 1200. Staff start a sale: 900 until 15:00:00.
14:00:00 getPrice("oolong") → { amount: 900, onSale: true }
cacheTag("price:oolong"), cacheLife({ stale: …, revalidate: …, expire: … })
14:59:47.5 12.5 seconds left → expire 12, if stale is 30
15:00:00 getPrice("oolong") → { amount: 1200, onSale: false }, cacheLife("max")
lib/catalog.ts, read-only. Import it as @/lib/catalog.
export type Tea = { slug: string; name: string; price: number };
/** A sale staff started: its price in cents, and when it ends, in milliseconds since 1970 like Date.now(). */
export type Sale = { slug: string; price: number; endsAt: number };
/** The shop's teas, prices in cents: a stand-in for its database. */
export const teas: Tea[] = [
{ slug: "green", name: "Green tea", price: 800 },
{ slug: "oolong", name: "Oolong tea", price: 1200 },
];
/**
* Sales staff have started. Starting one, or stopping one early, revalidates the tea's
* `price:<slug>` tag; a sale that runs to its end time just ends, and nothing is revalidated.
*/
export const sales: Sale[] = [];
export async function findTea(slug: string): Promise<Tea | undefined> {
return teas.find((tea) => tea.slug === slug);
}
/** The tea's sale, if staff started one. It may have ended already. */
export async function findSale(slug: string): Promise<Sale | undefined> {
return sales.find((sale) => sale.slug === slug);
}
const clock = useFakeTimers();
const startSale = (slug, price, seconds) => sales.push({ slug, price, endsAt: Date.now() + seconds * 1000 });
const priced = async (slug) => {
const before = cache.lives.length;
const price = await getPrice(slug);
const calls = cache.lives.length - before;
if (calls !== 1) throw new Error("getPrice should call cacheLife exactly once each time, but called it " + calls + " times");
return { price, life: cache.lives[before] };
};
const saleLife = (life) => {
if (typeof life !== "object" || life === null) throw new Error("A running sale needs a lifetime object, { stale, revalidate, expire }, but got cacheLife(" + JSON.stringify(life) + ")");
for (const key of ["stale", "revalidate", "expire"]) {
const value = life[key];
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error("Set " + key + " to a number of seconds, 0 or more, not " + JSON.stringify(value));
}
return life;
};
const accepted = (life) => {
if (life.revalidate > life.expire) throw new Error("revalidate (" + life.revalidate + ") is more than expire (" + life.expire + "), and Next.js throws for that");
if (life.expire > 0 && !(life.revalidate > 0)) throw new Error("revalidate should be above 0 while expire is, or every request starts a fresh copy in the background");
};
const { price, life } = await priced("green");
expect(price).toEqual({ amount: 800, onSale: false });
expect(life).toBe("max");
expect(cache.tags).toEqual(["price:green"]);
const clock = useFakeTimers();
const startSale = (slug, price, seconds) => sales.push({ slug, price, endsAt: Date.now() + seconds * 1000 });
const priced = async (slug) => {
const before = cache.lives.length;
const price = await getPrice(slug);
const calls = cache.lives.length - before;
if (calls !== 1) throw new Error("getPrice should call cacheLife exactly once each time, but called it " + calls + " times");
return { price, life: cache.lives[before] };
};
const saleLife = (life) => {
if (typeof life !== "object" || life === null) throw new Error("A running sale needs a lifetime object, { stale, revalidate, expire }, but got cacheLife(" + JSON.stringify(life) + ")");
for (const key of ["stale", "revalidate", "expire"]) {
const value = life[key];
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error("Set " + key + " to a number of seconds, 0 or more, not " + JSON.stringify(value));
}
return life;
};
const accepted = (life) => {
if (life.revalidate > life.expire) throw new Error("revalidate (" + life.revalidate + ") is more than expire (" + life.expire + "), and Next.js throws for that");
if (life.expire > 0 && !(life.revalidate > 0)) throw new Error("revalidate should be above 0 while expire is, or every request starts a fresh copy in the background");
};
startSale("oolong", 900, 3 * 60 * 60);
const { price, life } = await priced("oolong");
expect(price).toEqual({ amount: 900, onSale: true });
expect(cache.tags).toEqual(["price:oolong"]);
saleLife(life);
const clock = useFakeTimers();
const startSale = (slug, price, seconds) => sales.push({ slug, price, endsAt: Date.now() + seconds * 1000 });
const priced = async (slug) => {
const before = cache.lives.length;
const price = await getPrice(slug);
const calls = cache.lives.length - before;
if (calls !== 1) throw new Error("getPrice should call cacheLife exactly once each time, but called it " + calls + " times");
return { price, life: cache.lives[before] };
};
const saleLife = (life) => {
if (typeof life !== "object" || life === null) throw new Error("A running sale needs a lifetime object, { stale, revalidate, expire }, but got cacheLife(" + JSON.stringify(life) + ")");
for (const key of ["stale", "revalidate", "expire"]) {
const value = life[key];
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error("Set " + key + " to a number of seconds, 0 or more, not " + JSON.stringify(value));
}
return life;
};
const accepted = (life) => {
if (life.revalidate > life.expire) throw new Error("revalidate (" + life.revalidate + ") is more than expire (" + life.expire + "), and Next.js throws for that");
if (life.expire > 0 && !(life.revalidate > 0)) throw new Error("revalidate should be above 0 while expire is, or every request starts a fresh copy in the background");
};
startSale("oolong", 900, 3 * 60 * 60);
const life = saleLife((await priced("oolong")).life);
const worst = Math.max(life.stale, 30) + life.expire;
if (worst > 60) {
throw new Error("A shopper could see a price " + worst + " seconds old: a server copy up to " + life.expire + " seconds old (expire), then kept " + Math.max(life.stale, 30) + " more by the browser (stale, 30 at least)");
}
const clock = useFakeTimers();
const startSale = (slug, price, seconds) => sales.push({ slug, price, endsAt: Date.now() + seconds * 1000 });
const priced = async (slug) => {
const before = cache.lives.length;
const price = await getPrice(slug);
const calls = cache.lives.length - before;
if (calls !== 1) throw new Error("getPrice should call cacheLife exactly once each time, but called it " + calls + " times");
return { price, life: cache.lives[before] };
};
const saleLife = (life) => {
if (typeof life !== "object" || life === null) throw new Error("A running sale needs a lifetime object, { stale, revalidate, expire }, but got cacheLife(" + JSON.stringify(life) + ")");
for (const key of ["stale", "revalidate", "expire"]) {
const value = life[key];
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error("Set " + key + " to a number of seconds, 0 or more, not " + JSON.stringify(value));
}
return life;
};
const accepted = (life) => {
if (life.revalidate > life.expire) throw new Error("revalidate (" + life.revalidate + ") is more than expire (" + life.expire + "), and Next.js throws for that");
if (life.expire > 0 && !(life.revalidate > 0)) throw new Error("revalidate should be above 0 while expire is, or every request starts a fresh copy in the background");
};
startSale("oolong", 900, 3 * 60 * 60);
const life = saleLife((await priced("oolong")).life);
accepted(life);
expect(Math.max(life.stale, 30) + life.expire).toBe(60);
const clock = useFakeTimers();
const startSale = (slug, price, seconds) => sales.push({ slug, price, endsAt: Date.now() + seconds * 1000 });
const priced = async (slug) => {
const before = cache.lives.length;
const price = await getPrice(slug);
const calls = cache.lives.length - before;
if (calls !== 1) throw new Error("getPrice should call cacheLife exactly once each time, but called it " + calls + " times");
return { price, life: cache.lives[before] };
};
const saleLife = (life) => {
if (typeof life !== "object" || life === null) throw new Error("A running sale needs a lifetime object, { stale, revalidate, expire }, but got cacheLife(" + JSON.stringify(life) + ")");
for (const key of ["stale", "revalidate", "expire"]) {
const value = life[key];
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error("Set " + key + " to a number of seconds, 0 or more, not " + JSON.stringify(value));
}
return life;
};
const accepted = (life) => {
if (life.revalidate > life.expire) throw new Error("revalidate (" + life.revalidate + ") is more than expire (" + life.expire + "), and Next.js throws for that");
if (life.expire > 0 && !(life.revalidate > 0)) throw new Error("revalidate should be above 0 while expire is, or every request starts a fresh copy in the background");
};
startSale("oolong", 900, 60 * 60);
clock.tick(60 * 60 * 1000 - 12500);
let life = saleLife((await priced("oolong")).life);
expect(life.expire).toBe(Math.min(60 - Math.max(life.stale, 30), 12));
accepted(life);
clock.tick(12000);
const last = await priced("oolong");
expect(last.price).toEqual({ amount: 900, onSale: true });
life = saleLife(last.life);
expect(life.expire).toBe(0);
expect(life.revalidate).toBe(0);
const clock = useFakeTimers();
const startSale = (slug, price, seconds) => sales.push({ slug, price, endsAt: Date.now() + seconds * 1000 });
const priced = async (slug) => {
const before = cache.lives.length;
const price = await getPrice(slug);
const calls = cache.lives.length - before;
if (calls !== 1) throw new Error("getPrice should call cacheLife exactly once each time, but called it " + calls + " times");
return { price, life: cache.lives[before] };
};
const saleLife = (life) => {
if (typeof life !== "object" || life === null) throw new Error("A running sale needs a lifetime object, { stale, revalidate, expire }, but got cacheLife(" + JSON.stringify(life) + ")");
for (const key of ["stale", "revalidate", "expire"]) {
const value = life[key];
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error("Set " + key + " to a number of seconds, 0 or more, not " + JSON.stringify(value));
}
return life;
};
const accepted = (life) => {
if (life.revalidate > life.expire) throw new Error("revalidate (" + life.revalidate + ") is more than expire (" + life.expire + "), and Next.js throws for that");
if (life.expire > 0 && !(life.revalidate > 0)) throw new Error("revalidate should be above 0 while expire is, or every request starts a fresh copy in the background");
};
startSale("oolong", 900, 60);
clock.tick(60 * 1000);
const { price, life } = await priced("oolong");
expect(price).toEqual({ amount: 1200, onSale: false });
expect(life).toBe("max");
expect((await priced("green")).price).toEqual({ amount: 800, onSale: false });
const clock = useFakeTimers();
const startSale = (slug, price, seconds) => sales.push({ slug, price, endsAt: Date.now() + seconds * 1000 });
const priced = async (slug) => {
const before = cache.lives.length;
const price = await getPrice(slug);
const calls = cache.lives.length - before;
if (calls !== 1) throw new Error("getPrice should call cacheLife exactly once each time, but called it " + calls + " times");
return { price, life: cache.lives[before] };
};
const saleLife = (life) => {
if (typeof life !== "object" || life === null) throw new Error("A running sale needs a lifetime object, { stale, revalidate, expire }, but got cacheLife(" + JSON.stringify(life) + ")");
for (const key of ["stale", "revalidate", "expire"]) {
const value = life[key];
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error("Set " + key + " to a number of seconds, 0 or more, not " + JSON.stringify(value));
}
return life;
};
const accepted = (life) => {
if (life.revalidate > life.expire) throw new Error("revalidate (" + life.revalidate + ") is more than expire (" + life.expire + "), and Next.js throws for that");
if (life.expire > 0 && !(life.revalidate > 0)) throw new Error("revalidate should be above 0 while expire is, or every request starts a fresh copy in the background");
};
const { price, life } = await priced("matcha");
expect(price).toBe(null);
expect(life).toBe("max");
expect(cache.tags).toEqual(["price:matcha"]);
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(getPrice, "getPrice");
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).
I'm here to help with A flash sale price never a minute old. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.