| 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); | |
| } | |
| } | |