Prashikshak / API /src /middleware /cache.middleware.ts
Abhisingh-18's picture
Initial commit: Prashikshak - disaster management training platform
9a92a42
Raw
History Blame Contribute Delete
1.12 kB
import { Request, Response, NextFunction } from 'express';
import { getRedisClient } from '../util/redis.util';
export function cacheMiddleware(duration: number = 300) {
return async (req: Request, res: Response, next: NextFunction) => {
const redis = await getRedisClient();
const cacheKey = `cache:${req.originalUrl}:${req.userId || 'public'}`;
try {
const cachedData = await redis.get(cacheKey);
if (cachedData) {
return res.json(JSON.parse(cachedData));
}
// Override res.json to cache the response
const originalJson = res.json.bind(res);
res.json = function (data: any) {
redis.setEx(cacheKey, duration, JSON.stringify(data)).catch(console.error);
return originalJson(data);
};
next();
} catch (error) {
console.error('Cache error:', error);
next(); // Continue without cache on error
}
};
}
export async function invalidateCache(pattern: string) {
const redis = await getRedisClient();
const keys = await redis.keys(`cache:${pattern}`);
if (keys.length > 0) {
await redis.del(keys);
}
}