-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.ts
More file actions
63 lines (55 loc) · 1.46 KB
/
Copy pathcache.ts
File metadata and controls
63 lines (55 loc) · 1.46 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import Redis from 'ioredis';
import { CONFIG } from './config';
const INVOICE_TTL_SECONDS = 30;
let _client: Redis | null = null;
function getClient(): Redis | null {
if (!CONFIG.redisUrl) return null;
if (!_client) {
_client = new Redis(CONFIG.redisUrl);
_client.on('error', (err: Error) => {
console.error('[cache] Redis error:', err.message);
});
}
return _client;
}
export async function cacheGet(key: string): Promise<string | null> {
try {
return (await getClient()?.get(key)) ?? null;
} catch {
return null;
}
}
export async function cacheSet(
key: string,
value: string,
ttlSeconds = INVOICE_TTL_SECONDS
): Promise<void> {
try {
await getClient()?.set(key, value, 'EX', ttlSeconds);
} catch {
// Non-fatal: the next request will simply miss the cache.
}
}
export async function cacheDelete(key: string): Promise<void> {
try {
await getClient()?.del(key);
} catch {
// Non-fatal.
}
}
export async function cacheDeletePattern(pattern: string): Promise<void> {
const client = getClient();
if (!client) return;
try {
const keys = await client.keys(pattern);
if (keys.length > 0) {
await client.del(keys);
}
} catch {
// Non-fatal.
}
}
/** Invalidate all cache entries for a given invoice and every invoice list. */
export async function invalidateInvoiceCache(id: number): Promise<void> {
await Promise.all([cacheDelete(`invoice:${id}`), cacheDeletePattern('invoices:*')]);
}