xonecas.io
53129
Pa

PAT / files

PAT / src / lib / cache / index.ts

1.1 KB
1import ValKey from "iovalkey";
2
3const valkeyUrl = process.env.VALKEY_URL;
4if (!valkeyUrl) {
5  throw new Error("VALKEY_URL environment variable is not set");
6}
7
8const valkey = new ValKey(valkeyUrl);
9
10export async function setCache<T>(key: string, value: T, ttlMs?: number): Promise<void> {
11  try {
12    const serialized = JSON.stringify(value);
13
14    if (ttlMs && ttlMs > 0) {
15      // Convert milliseconds to seconds for Valkey
16      const ttlSeconds = Math.ceil(ttlMs / 1000);
17      await valkey.setex(key, ttlSeconds, serialized);
18    } else {
19      await valkey.set(key, serialized);
20    }
21  } catch {
22    // Don't throw - cache operations should continue even if persistence fails
23  }
24}
25
26export async function incrementCache(key: string): Promise<void> {
27  try {
28    await valkey.incr(key);
29  } catch {
30    // Don't throw - cache operations should continue even if persistence fails
31  }
32}
33
34export async function getCache<T>(key: string): Promise<T | null> {
35  try {
36    const serialized = await valkey.get(key);
37
38    if (!serialized) {
39      return null;
40    }
41
42    return JSON.parse(serialized) as T;
43  } catch {
44    return null;
45  }
46}