Switch to Custom Cache Handler

This commit is contained in:
Ahmad 2025-01-25 23:05:01 -05:00
parent 8900584267
commit 5ef2a3c67f
No known key found for this signature in database
GPG key ID: 8FD8A93530D182BF
4 changed files with 34 additions and 78 deletions

View file

@ -1,62 +1,41 @@
import { CacheHandler } from '@neshca/cache-handler';
import createLruHandler from '@neshca/cache-handler/local-lru';
import createRedisHandler from '@neshca/cache-handler/redis-stack';
import Redis from 'ioredis';
import Redis from 'ioredis'
CacheHandler.onCreation(async () => {
/** @type {import("@neshca/cache-handler").Handler | null} */
let handler;
const redis = new Redis(`${process.env.REDIS_URL}`)
let client;
try {
client = new Redis(`${process.env.REDIS_URL}`);
client.on('error', (error) => {
if (typeof process.env.NEXT_PRIVATE_DEBUG_CACHE !== 'undefined') {
console.error('Redis client error:', error);
}
});
} catch (error) {
console.warn('Failed to create Redis client:', error);
export default class CacheHandler {
constructor(options) {
this.options = options
}
if (client) {
try {
console.info('Connecting Redis client...');
async get(key) {
const data = await redis.get(key)
return data ? JSON.parse(data) : null
}
await client.connect();
console.info('Redis client connected.');
async set(key, data, ctx) {
const cacheData = {
value: data,
lastModified: Date.now(),
tags: ctx.tags,
}
await redis.set(key, JSON.stringify(cacheData))
}
handler = createRedisHandler({
client,
timeoutMs: 1000,
});
} catch (error) {
console.warn('Failed to connect Redis client:', error);
console.warn('Disconnecting the Redis client...');
client
.disconnect()
.then(() => {
console.info('Redis client disconnected.');
})
.catch(() => {
console.warn(
'Failed to quit the Redis client after failing to connect.'
);
});
handler = createLruHandler();
console.warn(
'Falling back to LRU handler because Redis client is not available.'
);
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)
}
}
}
}
return {
handlers: [handler],
};
});
export default CacheHandler;
resetRequestCache() {
// Implement request-specific cache reset if needed
}
}