(...args: Args)
| 59 | [id, ...args.map((a) => JSON.stringify(a))].join('|'); |
| 60 | |
| 61 | const get = async (...args: Args): Promise<T> => { |
| 62 | const key = buildKey(...args); |
| 63 | |
| 64 | // L1: in-memory cache |
| 65 | if (memTTL > 0) { |
| 66 | const mem = memCache.get(key); |
| 67 | if (mem && mem.expiry > Date.now()) { |
| 68 | return mem.value; |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | // L2: distributed cache (Redis / PostgreSQL / Map) |
| 73 | const cacheManager = await getCacheManager(); |
| 74 | const cachedValue = await cacheManager.get(key); |
| 75 | if (cachedValue) { |
| 76 | try { |
| 77 | const parsed = JSON.parse(String(cachedValue)) as T; |
| 78 | if (memTTL > 0) { |
| 79 | memCache.set(key, { value: parsed, expiry: Date.now() + memTTL }); |
| 80 | } |
| 81 | return parsed; |
| 82 | } catch (err) { |
| 83 | console.error(err); |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | // L3: fetch from DB |
| 88 | const realValue = await fetchFn(...args); |
| 89 | |
| 90 | if (realValue != null) { |
| 91 | await cacheManager.set(key, JSON.stringify(realValue)); |
| 92 | |
| 93 | if (memTTL > 0) { |
| 94 | memCache.set(key, { value: realValue, expiry: Date.now() + memTTL }); |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | return realValue; |
| 99 | }; |
| 100 | |
| 101 | const update = (...args: Args) => { |
| 102 | const key = buildKey(...args); |
no test coverage detected