File size: 612 Bytes
3845a5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { redis } from '../../config/redis.js';

export const cached = async (key, ttlSeconds, fetchFn) => {
  if (!redis) return fetchFn();

  try {
    const hit = await redis.get(key);
    if (hit) return JSON.parse(hit);
  } catch {
    return fetchFn();
  }

  const value = await fetchFn();

  try {
    await redis.setEx(key, ttlSeconds, JSON.stringify(value));
  } catch {
    // cache write failure is non-critical
  }

  return value;
};

export const invalidateCache = async (...keys) => {
  if (!redis || !keys.length) return;
  try {
    await redis.del(keys);
  } catch {
    // non-critical
  }
};