forked from SmartDropLabs/smartdrop-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.js
More file actions
66 lines (58 loc) · 1.47 KB
/
Copy pathcache.js
File metadata and controls
66 lines (58 loc) · 1.47 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
const Redis = require('ioredis');
const config = require('../config');
const logger = require('../logger');
let client = null;
function getClient() {
if (!client) {
client = new Redis(config.redis.url, {
lazyConnect: true,
enableOfflineQueue: false,
});
client.on('error', (err) => {
logger.error('Redis connection error', { error: err.message });
});
client.on('connect', () => {
logger.info('Redis connected');
});
client.on('ready', () => {
logger.info('Redis ready');
});
// Kick off the initial connection without blocking or throwing here;
// errors are surfaced via the 'error' event above.
client.connect().catch(() => {});
}
return client;
}
function isConnected() {
return client !== null && client.status === 'ready';
}
async function get(key) {
const redis = getClient();
const data = await redis.get(key);
if (!data) return null;
try {
return JSON.parse(data);
} catch {
return data;
}
}
async function set(key, value, ttlSeconds) {
const redis = getClient();
const serialized = JSON.stringify(value);
if (ttlSeconds) {
await redis.setex(key, ttlSeconds, serialized);
} else {
await redis.set(key, serialized);
}
}
async function del(key) {
const redis = getClient();
await redis.del(key);
}
async function disconnect() {
if (client) {
await client.quit();
client = null;
}
}
module.exports = { get, set, del, disconnect, getClient, isConnected };