-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredis.ts
More file actions
84 lines (75 loc) · 2.03 KB
/
Copy pathredis.ts
File metadata and controls
84 lines (75 loc) · 2.03 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Redis } from "@upstash/redis";
// Lazy initialization — tidak diinisialisasi saat module di-load,
// hanya saat pertama kali dipakai
let _redis: Redis | null = null;
export function getRedisClient(): Redis | null {
if (
!process.env.UPSTASH_REDIS_REST_URL ||
!process.env.UPSTASH_REDIS_REST_TOKEN
) {
return null;
}
if (!_redis) {
_redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL,
token: process.env.UPSTASH_REDIS_REST_TOKEN,
});
}
return _redis;
}
export async function cachedQuery<T>(
key: string,
fetcher: () => Promise<T>,
ttlSeconds: number = 300,
): Promise<T> {
const redis = getRedisClient();
// Kalau Redis tidak tersedia (build time atau env missing),
// langsung fetch dari DB tanpa caching
if (!redis) {
return fetcher();
}
try {
const cachedData = await redis.get<T>(key);
if (cachedData) return cachedData;
} catch (error: any) {
if (
error &&
(error.digest === "DYNAMIC_SERVER_USAGE" ||
error.message?.includes("Dynamic server usage"))
) {
throw error;
}
console.error(`[Redis] Error fetching key "${key}":`, error);
}
const freshData = await fetcher();
try {
await redis.set(key, freshData, { ex: ttlSeconds });
} catch (error: any) {
if (
error &&
(error.digest === "DYNAMIC_SERVER_USAGE" ||
error.message?.includes("Dynamic server usage"))
) {
throw error;
}
console.error(`[Redis] Error setting key "${key}":`, error);
}
return freshData;
}
export async function invalidateCache(...keys: string[]) {
const redis = getRedisClient();
if (!redis || keys.length === 0) return;
try {
await redis.del(...keys);
} catch (error: any) {
if (
error &&
(error.digest === "DYNAMIC_SERVER_USAGE" ||
error.message?.includes("Dynamic server usage"))
) {
throw error;
}
console.error(`[Redis] Error invalidating keys ${keys.join(", ")}:`, error);
}
}