This repository has been archived by the owner on May 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CacheManager.js
executable file
·57 lines (52 loc) · 1.72 KB
/
CacheManager.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
const redis = require('redis');
const { promisify } = require('util');
module.exports = class CacheManager {
constructor (logger) {
this.logger = logger.child({ subject: this.constructor.name });
}
async init () {
if (!process.env.REDIS_HOST || !process.env.REDIS_PORT) {
console.error('[CacheManager] one of environment REDIS_* is not defined');
this.logger.error(`one of environment REDIS_* is not defined`);
return;
}
return new Promise((resolve, reject) => {
console.log('connection to redis...');
this.client = redis.createClient({
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
});
this.client.on('error', err => {
this.logger.error(err);
reject(err);
});
this.client.on('ready', () => {
console.log('redis connected');
resolve();
});
});
}
setObject (key, obj, expireSeconds = null) {
this.client.set(key, JSON.stringify(obj), (err, res) => {
if (err) {
this.logger.error(err);
return;
}
this.logger.info(`set ${key} for ${expireSeconds} seconds`);
});
if (expireSeconds) {
this.client.expire(key, expireSeconds);
}
}
async getObject (key) {
// see https://github.com/NodeRedis/node_redis#promises
const result = await promisify(this.client.get).bind(this.client)(key);
if (result) {
return JSON.parse(result);
}
return result;
}
stop () {
this.client.end(true);
}
};