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'
const redis = new Redis(`${process.env.REDIS_URL}`)
import { redis } from '@/lib/redis';
export default class CacheHandler {
constructor(options) {
this.options = options
this.options = options;
}
async get(key) {
const data = await redis.get(key)
return data ? JSON.parse(data) : null
try {
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) {
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);
}
await redis.set(key, JSON.stringify(cacheData))
}
async revalidateTag(tags) {
tags = [tags].flat()
const keys = await redis.keys('*')
try {
tags = [tags].flat();
const keys = await redis.keys('*');
for (const key of keys) {
const value = await redis.get(key)
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)
const parsed = JSON.parse(value);
if (parsed.tags.some((tag) => tags.includes(tag))) {
await redis.del(key);
}
}
}
} catch (error) {
console.error('Cache RevalidateTag Error:', error);
}
}
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;