tasko/cache-handler.mjs

56 lines
1.3 KiB
JavaScript
Raw Normal View History

2025-01-26 20:54:53 +00:00
import redis from './lib/redis.js';
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(),
2025-01-26 20:44:15 +00:00
tags: ctx.tags || [],
2025-01-26 04:55:00 +00:00
};
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);
2025-01-26 20:44:15 +00:00
if (value && tags.length > 0) {
2025-01-26 04:55:00 +00:00
const parsed = JSON.parse(value);
2025-01-26 20:44:15 +00:00
if (
Array.isArray(parsed.tags) &&
parsed.tags.some((tag) => tags.includes(tag))
) {
2025-01-26 04:55:00 +00:00
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
}