Skip to content

Commit 464dba5

Browse files
committed
feat: implement background cache updater for RSVP count
1 parent c245857 commit 464dba5

File tree

1 file changed

+30
-13
lines changed

1 file changed

+30
-13
lines changed

src/pages/api/rsvp.ts

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// src/pages/api/rsvp.ts
12
import { NextApiRequest, NextApiResponse } from "next";
23

34
async function getCount() {
@@ -32,17 +33,33 @@ let cached = { value: -1, updated: 0 };
3233
// Cache duration in milliseconds
3334
const CACHE_DURATION = 30000;
3435

35-
export default async function handler(_req: NextApiRequest, res: NextApiResponse) {
36-
const now = Date.now();
37-
if (now - cached.updated > CACHE_DURATION) {
38-
try {
39-
const count = await getCount();
40-
cached = { value: count, updated: now };
41-
console.log("cached value", cached.value, "updatedAt", new Date(cached.updated).toISOString());
42-
} catch (err: unknown) {
43-
console.error("getCount failed:", err);
44-
res.status(500).json({ error: "couldnt get count" });
45-
}
36+
// Extend global to hold a single timer across module reloads (avoid duplicate timers in dev)
37+
declare global {
38+
var __RSVP_CACHE_TIMER__: NodeJS.Timeout | undefined;
39+
}
40+
41+
async function updateCache() {
42+
try {
43+
const count = await getCount();
44+
cached = { value: count, updated: Date.now() };
45+
console.log("cached value", cached.value, "updatedAt", new Date(cached.updated).toISOString());
46+
} catch (err: unknown) {
47+
console.error("updateCache failed:", err);
48+
// keep previous cached value
4649
}
47-
res.status(200).json({ count: cached.value });
48-
}
50+
}
51+
52+
// Start background updater once per server instance
53+
if (!global.__RSVP_CACHE_TIMER__) {
54+
// initial immediate update (fire-and-forget)
55+
updateCache().catch((e) => console.error("initial update failed:", e));
56+
57+
// schedule periodic updates
58+
global.__RSVP_CACHE_TIMER__ = setInterval(() => {
59+
updateCache().catch((e) => console.error("scheduled update failed:", e));
60+
}, CACHE_DURATION);
61+
}
62+
63+
export default function handler(_req: NextApiRequest, res: NextApiResponse) {
64+
res.status(200).json({ count: cached.value, updatedAt: cached.updated });
65+
}

0 commit comments

Comments
 (0)