-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathcache-handler.js
More file actions
67 lines (56 loc) · 1.62 KB
/
cache-handler.js
File metadata and controls
67 lines (56 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const cache = new Map()
const pendingSets = new Map()
// TODO: Replace basic in-memory cache with Redis implementation using nextjs-cache-handler library
module.exports = {
async get(cacheKey, softTags) {
console.log("[Cache Handler] get called", cacheKey)
// Wait for any pending set operation to complete
const pendingPromise = pendingSets.get(cacheKey)
if (pendingPromise) {
await pendingPromise
}
const entry = cache.get(cacheKey)
if (!entry) {
return undefined
}
// Check if entry has expired
const now = Date.now()
if (now > entry.timestamp + entry.revalidate * 1000) {
return undefined
}
return entry
},
async set(cacheKey, pendingEntry) {
console.log("[Cache Handler] set called", cacheKey)
// Create a promise to track this set operation
let resolvePending
const pendingPromise = new Promise((resolve) => {
resolvePending = resolve
})
pendingSets.set(cacheKey, pendingPromise)
try {
// Wait for the entry to be ready
const entry = await pendingEntry
// Store the entry in the cache
cache.set(cacheKey, entry)
} finally {
resolvePending()
pendingSets.delete(cacheKey)
}
},
async refreshTags() {
// No-op for in-memory cache
},
async getExpiration(tags) {
// Return 0 to indicate no tags have been revalidated
return 0
},
async updateTags(tags, durations) {
// Implement tag-based invalidation
for (const [key, entry] of cache.entries()) {
if (entry.tags.some((tag) => tags.includes(tag))) {
cache.delete(key)
}
}
},
}