From 20055c396123c28f5527194c7557348ac3a0d0fa Mon Sep 17 00:00:00 2001 From: Ahmad <103906421+ahmadk953@users.noreply.github.com> Date: Sat, 25 Jan 2025 23:55:00 -0500 Subject: [PATCH] Added Error Handling to Cache --- cache-handler.mjs | 53 ++++++++++++++++++++++++++++------------------- lib/redis.ts | 13 ++++++++++++ 2 files changed, 45 insertions(+), 21 deletions(-) create mode 100644 lib/redis.ts diff --git a/cache-handler.mjs b/cache-handler.mjs index 574309e..d024d1c 100644 --- a/cache-handler.mjs +++ b/cache-handler.mjs @@ -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) { - const cacheData = { - value: data, - lastModified: Date.now(), - tags: ctx.tags, + 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('*') - 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) + 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); + } } } + } catch (error) { + console.error('Cache RevalidateTag Error:', error); } } resetRequestCache() { - // Implement request-specific cache reset if needed + // TODO: Implement request-specific cache reset if needed } -} \ No newline at end of file +} diff --git a/lib/redis.ts b/lib/redis.ts new file mode 100644 index 0000000..bc0e1fe --- /dev/null +++ b/lib/redis.ts @@ -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;