forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.js
More file actions
276 lines (243 loc) · 5.64 KB
/
Copy pathcache.js
File metadata and controls
276 lines (243 loc) · 5.64 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import { getRedisClient, isRedisReady } from "../config/redis.js";
import logger from "../config/logger.js";
/**
* Cache TTL (Time To Live) in seconds
*/
export const CACHE_TTL = {
SHORT: 60 * 3, // 3 minutes
MEDIUM: 60 * 10, // 10 minutes
LONG: 60 * 30, // 30 minutes
VERY_LONG: 60 * 60, // 1 hour
// Specific entities
COURSES: 60 * 15, // 15 minutes
BOOKS: 60 * 15, // 15 minutes
USERS: 60 * 10, // 10 minutes
SPACES: 60 * 5, // 5 minutes
REELS: 60 * 3, // 3 minutes
SEARCH: 60 * 5, // 5 minutes
EDUCATORS: 60 * 10, // 10 minutes
};
/**
* Cache key prefixes
*/
export const CACHE_KEYS = {
COURSES: "courses:",
COURSE: "course:",
BOOKS: "books:",
BOOK: "book:",
USERS: "users:",
USER: "user:",
SPACES: "spaces:",
SPACE: "space:",
REELS: "reels:",
REEL: "reel:",
SEARCH: "search:",
EDUCATORS: "educators:",
};
/**
* Set cache
*/
export const setCache = async (key, value, ttl = CACHE_TTL.MEDIUM) => {
try {
if (!isRedisReady()) {
logger.warn("⚠️ Redis not available, skipping cache set");
return false;
}
const client = getRedisClient();
const stringValue = JSON.stringify(value);
await client.setEx(key, ttl, stringValue);
logger.debug(`✅ Cache set: ${key} (TTL: ${ttl}s)`);
return true;
} catch (error) {
logger.error(`❌ Cache set error for key ${key}:`, error);
return false;
}
};
/**
* Get cache
*/
export const getCache = async (key) => {
try {
if (!isRedisReady()) {
return null;
}
const client = getRedisClient();
const value = await client.get(key);
if (value) {
logger.debug(`✅ Cache hit: ${key}`);
return JSON.parse(value);
}
logger.debug(`❌ Cache miss: ${key}`);
return null;
} catch (error) {
logger.error(`❌ Cache get error for key ${key}:`, error);
return null;
}
};
/**
* Delete cache
*/
export const deleteCache = async (key) => {
try {
if (!isRedisReady()) {
return false;
}
const client = getRedisClient();
await client.del(key);
logger.debug(`🗑️ Cache deleted: ${key}`);
return true;
} catch (error) {
logger.error(`❌ Cache delete error for key ${key}:`, error);
return false;
}
};
/**
* Delete multiple keys matching pattern
*/
export const deleteCachePattern = async (pattern) => {
try {
if (!isRedisReady()) {
return false;
}
const client = getRedisClient();
const keys = await client.keys(pattern);
if (keys.length > 0) {
await client.del(keys);
logger.debug(
`🗑️ Deleted ${keys.length} cache keys matching: ${pattern}`
);
}
return true;
} catch (error) {
logger.error(
`❌ Cache pattern delete error for pattern ${pattern}:`,
error
);
return false;
}
};
/**
* Check if key exists in cache
*/
export const cacheExists = async (key) => {
try {
if (!isRedisReady()) {
return false;
}
const client = getRedisClient();
const exists = await client.exists(key);
return exists === 1;
} catch (error) {
logger.error(`❌ Cache exists error for key ${key}:`, error);
return false;
}
};
/**
* Get cache with fallback
* If cache miss, execute fallback function and cache the result
*/
export const getCacheOrSet = async (
key,
fallbackFn,
ttl = CACHE_TTL.MEDIUM
) => {
try {
// Try to get from cache
const cached = await getCache(key);
if (cached !== null) {
return cached;
}
// Cache miss - execute fallback
logger.debug(`🔄 Executing fallback for: ${key}`);
const result = await fallbackFn();
// Cache the result
await setCache(key, result, ttl);
return result;
} catch (error) {
logger.error(`❌ getCacheOrSet error for key ${key}:`, error);
// If error, just return fallback result without caching
return await fallbackFn();
}
};
/**
* Increment cache value
*/
export const incrementCache = async (key, amount = 1) => {
try {
if (!isRedisReady()) {
return null;
}
const client = getRedisClient();
const result = await client.incrBy(key, amount);
return result;
} catch (error) {
logger.error(`❌ Cache increment error for key ${key}:`, error);
return null;
}
};
/**
* Set cache with expiry at specific time
*/
export const setCacheExpireAt = async (key, value, timestamp) => {
try {
if (!isRedisReady()) {
return false;
}
const client = getRedisClient();
const stringValue = JSON.stringify(value);
await client.set(key, stringValue);
await client.expireAt(key, timestamp);
logger.debug(`✅ Cache set with expireAt: ${key}`);
return true;
} catch (error) {
logger.error(`❌ Cache expireAt error for key ${key}:`, error);
return false;
}
};
/**
* Get remaining TTL for a key
*/
export const getCacheTTL = async (key) => {
try {
if (!isRedisReady()) {
return null;
}
const client = getRedisClient();
const ttl = await client.ttl(key);
return ttl;
} catch (error) {
logger.error(`❌ Get TTL error for key ${key}:`, error);
return null;
}
};
/**
* Flush all cache (use with caution!)
*/
export const flushAllCache = async () => {
try {
if (!isRedisReady()) {
return false;
}
const client = getRedisClient();
await client.flushAll();
logger.warn("⚠️ All cache flushed!");
return true;
} catch (error) {
logger.error("❌ Flush all cache error:", error);
return false;
}
};
export default {
setCache,
getCache,
deleteCache,
deleteCachePattern,
cacheExists,
getCacheOrSet,
incrementCache,
setCacheExpireAt,
getCacheTTL,
flushAllCache,
CACHE_TTL,
CACHE_KEYS,
};