Added Error Handling to Cache

This commit is contained in:
Ahmad 2025-01-25 23:55:00 -05:00
parent 5ef2a3c67f
commit 20055c3961
No known key found for this signature in database
GPG key ID: 8FD8A93530D182BF
2 changed files with 45 additions and 21 deletions

View file

@ -1,41 +1,52 @@
import Redis from 'ioredis' import { redis } from '@/lib/redis';
const redis = new Redis(`${process.env.REDIS_URL}`)
export default class CacheHandler { export default class CacheHandler {
constructor(options) { constructor(options) {
this.options = options this.options = options;
} }
async get(key) { async get(key) {
const data = await redis.get(key) try {
return data ? JSON.parse(data) : null const data = await redis.get(key);
return data ? JSON.parse(data) : null;
} catch (error) {
console.error('Cache Get Error:', error);
return null;
}
} }
async set(key, data, ctx) { async set(key, data, ctx) {
try {
const cacheData = { const cacheData = {
value: data, value: data,
lastModified: Date.now(), lastModified: Date.now(),
tags: ctx.tags, tags: ctx.tags,
};
await redis.set(key, JSON.stringify(cacheData));
} catch (error) {
console.error('Cache Set Error:', error);
} }
await redis.set(key, JSON.stringify(cacheData))
} }
async revalidateTag(tags) { async revalidateTag(tags) {
tags = [tags].flat() try {
const keys = await redis.keys('*') tags = [tags].flat();
const keys = await redis.keys('*');
for (const key of keys) { for (const key of keys) {
const value = await redis.get(key) const value = await redis.get(key);
if (value) { if (value) {
const parsed = JSON.parse(value) const parsed = JSON.parse(value);
if (parsed.tags.some(tag => tags.includes(tag))) { if (parsed.tags.some((tag) => tags.includes(tag))) {
await redis.del(key) await redis.del(key);
} }
} }
} }
} catch (error) {
console.error('Cache RevalidateTag Error:', error);
}
} }
resetRequestCache() { resetRequestCache() {
// Implement request-specific cache reset if needed // TODO: Implement request-specific cache reset if needed
} }
} }

13
lib/redis.ts Normal file
View file

@ -0,0 +1,13 @@
import Redis from 'ioredis';
let redis;
if (!redis) {
redis = new Redis(process.env.REDIS_URL);
redis.on('error', (err) => {
console.error('Redis Client Error:', err);
});
}
export default redis;