2025-01-26 04:05:01 +00:00
|
|
|
import Redis from 'ioredis'
|
2025-01-19 00:14:19 +00:00
|
|
|
|
2025-01-26 04:05:01 +00:00
|
|
|
const redis = new Redis(`${process.env.REDIS_URL}`)
|
2025-01-24 03:01:17 +00:00
|
|
|
|
2025-01-26 04:05:01 +00:00
|
|
|
export default class CacheHandler {
|
|
|
|
constructor(options) {
|
|
|
|
this.options = options
|
2025-01-19 00:14:19 +00:00
|
|
|
}
|
|
|
|
|
2025-01-26 04:05:01 +00:00
|
|
|
async get(key) {
|
|
|
|
const data = await redis.get(key)
|
|
|
|
return data ? JSON.parse(data) : null
|
|
|
|
}
|
2025-01-19 00:14:19 +00:00
|
|
|
|
2025-01-26 04:05:01 +00:00
|
|
|
async set(key, data, ctx) {
|
|
|
|
const cacheData = {
|
|
|
|
value: data,
|
|
|
|
lastModified: Date.now(),
|
|
|
|
tags: ctx.tags,
|
2025-01-24 03:01:17 +00:00
|
|
|
}
|
2025-01-26 04:05:01 +00:00
|
|
|
await redis.set(key, JSON.stringify(cacheData))
|
2025-01-19 00:14:19 +00:00
|
|
|
}
|
|
|
|
|
2025-01-26 04:05:01 +00:00
|
|
|
async revalidateTag(tags) {
|
|
|
|
tags = [tags].flat()
|
|
|
|
const keys = await redis.keys('*')
|
|
|
|
for (const key of keys) {
|
|
|
|
const value = await redis.get(key)
|
|
|
|
if (value) {
|
|
|
|
const parsed = JSON.parse(value)
|
|
|
|
if (parsed.tags.some(tag => tags.includes(tag))) {
|
|
|
|
await redis.del(key)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2025-01-19 00:14:19 +00:00
|
|
|
|
2025-01-26 04:05:01 +00:00
|
|
|
resetRequestCache() {
|
|
|
|
// Implement request-specific cache reset if needed
|
|
|
|
}
|
|
|
|
}
|