1+ // src/pages/api/rsvp.ts
12import { NextApiRequest , NextApiResponse } from "next" ;
23
34async function getCount ( ) {
@@ -32,17 +33,33 @@ let cached = { value: -1, updated: 0 };
3233// Cache duration in milliseconds
3334const 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