-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.js
59 lines (49 loc) · 1.49 KB
/
redis.js
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
const redis = require('redis');
let client = null;
async function ensureConnection() {
if (!client) {
if (process.env.REDIS_HOST && process.env.REDIS_PORT) {
client = redis.createClient({
socket: {
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT
},
});
await openConnection();
}
} else if (!client.isReady) {
await openConnection();
}
}
async function openConnection() {
if (!client.isOpen) await client.connect().catch(console.error);
await client.ping().then(console.log).catch(console.error);
}
async function setData(store, key, value) {
await ensureConnection();
const data = typeof value === 'object' ? JSON.stringify(value) : value;
await client.set(`${store}_${key}`, data);
return true;
}
async function getData(store, key) {
await ensureConnection();
return client.get(`${store}_${key}`)
.then((reply) => {
console.log(`Data retrieved successfully: ${reply}`);
try {
return JSON.parse(reply);
} catch(e) {
console.error('Error parsing data: ', e.message);
throw e;
}
});
}
async function deleteKey(store, key) {
await ensureConnection();
return client.del(`${store}_${key}`);
}
module.exports = {
setData,
getData,
deleteKey,
};