Skip to content

Commit 712a046

Browse files
committed
Invalidate calendar cache on calendar URLs changed
1 parent 05d2724 commit 712a046

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

pages/api/schema.ics.ts

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,19 +29,30 @@ function getCalendarCacheExpiration(
2929

3030
let cachedCalendarBody: string | null = null
3131
let cachedCalendarTime: number = 0
32+
let cachedCalendarUrls: string = ''
3233

3334
/** Get the cached calendar body, or nothing if unset or expired. */
34-
function getCachedCalendarBody(): string | null {
35+
async function getCachedCalendarBody(): Promise<string | null> {
3536
const cacheAgeMinutes = (Date.now() - cachedCalendarTime) / ONE_MINUTE_MS
36-
console.log(`Age: ${cacheAgeMinutes}`)
37-
const isExpired = cacheAgeMinutes >= calendarCacheExpiration
38-
return isExpired ? null : cachedCalendarBody
37+
if (cacheAgeMinutes >= calendarCacheExpiration) {
38+
// Cache invalidated by expiration time
39+
return null
40+
}
41+
42+
const calendarUrls = await (await getCalendarUrls()).join()
43+
if (calendarUrls != cachedCalendarUrls) {
44+
// Cache invalidated by changed URLs
45+
return null
46+
}
47+
48+
return cachedCalendarBody
3949
}
4050

4151
/** Save a calendar body to the cache and save the cached time. */
42-
function cacheCalendarBody(calendarBody: string) {
52+
async function cacheCalendarBody(calendarBody: string) {
4353
cachedCalendarBody = calendarBody
4454
cachedCalendarTime = Date.now()
55+
cachedCalendarUrls = (await getCalendarUrls()).join()
4556
}
4657

4758
async function getCalendarUrls(): Promise<string[]> {
@@ -120,8 +131,7 @@ async function createMergedCalendar(
120131
* @returns The new merged calendar, or the cached calendar if it exists and is not expired.
121132
*/
122133
async function createCalendarBodyWithCache(productId: string): Promise<string> {
123-
const cached = getCachedCalendarBody()
124-
console.log(`Cached: ` + !!cached)
134+
const cached = await getCachedCalendarBody()
125135
if (cached) {
126136
return cached
127137
}

0 commit comments

Comments
 (0)