forked from Prompt-Hash-Stellar/prompt-hash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcacheService.ts
More file actions
68 lines (59 loc) · 1.51 KB
/
Copy pathcacheService.ts
File metadata and controls
68 lines (59 loc) · 1.51 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
64
65
66
67
68
import { createClient, type RedisClientType } from "redis";
let client: RedisClientType | null = null;
async function getClient(): Promise<RedisClientType | null> {
if (!process.env.REDIS_URL) return null;
if (client) return client;
client = createClient({ url: process.env.REDIS_URL }) as RedisClientType;
client.on("error", (err) => {
console.error("[cache] Redis error:", err);
client = null;
});
await client.connect();
return client;
}
const DEFAULT_TTL = 60; // seconds
export async function cacheGet(key: string): Promise<string | null> {
try {
const c = await getClient();
if (!c) return null;
return c.get(key);
} catch {
return null;
}
}
export async function cacheSet(
key: string,
value: string,
ttlSeconds = DEFAULT_TTL,
): Promise<void> {
try {
const c = await getClient();
if (!c) return;
await c.set(key, value, { EX: ttlSeconds });
} catch {
// cache miss is non-fatal
}
}
export async function cacheDel(...keys: string[]): Promise<void> {
try {
const c = await getClient();
if (!c) return;
await c.del(keys);
} catch {
// non-fatal
}
}
export async function cacheDelPattern(pattern: string): Promise<void> {
try {
const c = await getClient();
if (!c) return;
const keys = await c.keys(pattern);
if (keys.length) await c.del(keys);
} catch {
// non-fatal
}
}
export const CACHE_KEYS = {
promptList: (query: string) => `prompts:list:${query}`,
promptDetail: (id: string) => `prompts:detail:${id}`,
};