tasko/cache-handler.mjs

53 lines
1.2 KiB
JavaScript
Raw Normal View History

2025-01-26 04:55:00 +00:00
import { redis } from '@/lib/redis';
2025-01-24 03:01:17 +00:00
2025-01-26 04:05:01 +00:00
export default class CacheHandler {
constructor(options) {
2025-01-26 04:55:00 +00:00
this.options = options;
}
2025-01-26 04:05:01 +00:00
async get(key) {
2025-01-26 04:55:00 +00:00
try {
const data = await redis.get(key);
return data ? JSON.parse(data) : null;
} catch (error) {
console.error('Cache Get Error:', error);
return null;
}
2025-01-26 04:05:01 +00:00
}
2025-01-26 04:05:01 +00:00
async set(key, data, ctx) {
2025-01-26 04:55:00 +00:00
try {
const cacheData = {
value: data,
lastModified: Date.now(),
tags: ctx.tags,
};
await redis.set(key, JSON.stringify(cacheData));
} catch (error) {
console.error('Cache Set Error:', error);
2025-01-24 03:01:17 +00:00
}
}
2025-01-26 04:05:01 +00:00
async revalidateTag(tags) {
2025-01-26 04:55:00 +00:00
try {
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-26 04:05:01 +00:00
}
}
2025-01-26 04:55:00 +00:00
} catch (error) {
console.error('Cache RevalidateTag Error:', error);
2025-01-26 04:05:01 +00:00
}
}
2025-01-26 04:05:01 +00:00
resetRequestCache() {
2025-01-26 04:55:00 +00:00
// TODO: Implement request-specific cache reset if needed
2025-01-26 04:05:01 +00:00
}
2025-01-26 04:55:00 +00:00
}