forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcacheService.js
More file actions
96 lines (87 loc) · 2.14 KB
/
Copy pathcacheService.js
File metadata and controls
96 lines (87 loc) · 2.14 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
const { client } = require('../lib/redis');
/**
* Service to manage Redis caching layer.
* Requirements: #358 Caching Layer
*/
class CacheService {
constructor() {
this.client = client;
this.DEFAULT_TTL = 3600; // 1 hour default
}
/**
* Get a cached value by key.
*/
async get(key) {
try {
const value = await this.client.get(key);
return value ? JSON.parse(value) : null;
} catch (err) {
console.error(`[Cache] Error getting key=${key}`, err);
return null;
}
}
/**
* Set a cached value with TTL.
*/
async set(key, value, ttl = this.DEFAULT_TTL) {
try {
await this.client.setEx(key, ttl, JSON.stringify(value));
return true;
} catch (err) {
console.error(`[Cache] Error setting key=${key}`, err);
return false;
}
}
/**
* Invalidate a specific key.
*/
async del(key) {
try {
await this.client.del(key);
return true;
} catch (err) {
console.error(`[Cache] Error deleting key=${key}`, err);
return false;
}
}
/**
* Force invalidate by pattern (e.g., 'user:*').
* Warning: keys() can be slow on large datasets, use with caution.
*/
async invalidatePattern(pattern) {
try {
const keys = await this.client.keys(pattern);
if (keys.length > 0) {
await this.client.del(keys);
console.info(`[Cache] Invalidated ${keys.length} keys matching ${pattern}`);
}
return true;
} catch (err) {
console.error(`[Cache] Error invalidating pattern=${pattern}`, err);
return false;
}
}
/**
* Track / monitor cache health.
*/
async getHealth() {
try {
const startTime = Date.now();
await this.client.ping();
const latency = Date.now() - startTime;
const info = await this.client.info('memory');
const usedMemory = info.match(/used_memory_human:(.*)/)?.[1] || 'unknown';
return {
status: 'healthy',
latencyMs: latency,
usedMemory,
};
} catch (err) {
return {
status: 'unhealthy',
error: err.message,
};
}
}
}
module.exports = new CacheService();