File size: 1,120 Bytes
9a92a42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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);
  }
}