2020-09-01 23:43:54 +02:00
|
|
|
const Redis = require('ioredis');
|
2020-08-26 04:54:58 +02:00
|
|
|
const winston = require('winston');
|
2011-11-19 01:52:18 +01:00
|
|
|
|
2020-09-01 23:43:54 +02:00
|
|
|
class RedisDocumentStore {
|
2011-11-22 04:03:50 +01:00
|
|
|
|
2020-09-01 23:43:54 +02:00
|
|
|
constructor(options = {}){
|
|
|
|
this.expire = options.expire;
|
|
|
|
const redisClient = new Redis(options.redisOptions);
|
|
|
|
|
|
|
|
redisClient.on('error', err => {
|
|
|
|
winston.error('redisClient errored', {error: err});
|
|
|
|
process.exit(1);
|
|
|
|
});
|
|
|
|
redisClient.on('ready', () => {
|
|
|
|
winston.info(`connected to redis on ${redisClient.options.host}:${redisClient.options.port}/${redisClient.options.db}`);
|
|
|
|
});
|
|
|
|
this.client = redisClient;
|
|
|
|
winston.info('initialized redis client');
|
2020-08-28 04:39:03 +02:00
|
|
|
}
|
2011-11-19 01:52:18 +01:00
|
|
|
|
2020-09-02 16:16:54 +02:00
|
|
|
async set(key, data, skipExpire){
|
|
|
|
return await this.client.set(key, data)
|
|
|
|
.then(() => {
|
|
|
|
if (!skipExpire) this.setExpiration(key);
|
|
|
|
return true;
|
|
|
|
})
|
|
|
|
.catch(err => {
|
|
|
|
winston.error('failed to set redis document', {error: err});
|
|
|
|
return false;
|
|
|
|
});
|
2020-08-28 04:39:03 +02:00
|
|
|
}
|
2018-09-19 16:37:34 +02:00
|
|
|
|
2020-09-02 16:16:54 +02:00
|
|
|
async get(key, skipExpire){
|
|
|
|
return await this.client.get(key)
|
|
|
|
.then(data => {
|
|
|
|
if (!skipExpire) this.setExpiration(key);
|
|
|
|
return data;
|
|
|
|
})
|
|
|
|
.catch(err => {
|
|
|
|
winston.error('failed to get redis document', {key: key, error: err});
|
|
|
|
return null;
|
|
|
|
});
|
2020-08-28 04:39:03 +02:00
|
|
|
}
|
2011-11-22 04:03:50 +01:00
|
|
|
|
2020-09-01 23:43:54 +02:00
|
|
|
async setExpiration(key){
|
|
|
|
if (!this.expire) return;
|
|
|
|
await this.client.expire(key, this.expire).catch(err => {
|
2020-09-02 16:16:54 +02:00
|
|
|
winston.warn('failed to set redis key expiry', {key: key, error: err});
|
2020-09-01 23:43:54 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2011-11-19 01:52:18 +01:00
|
|
|
|
2020-09-01 23:43:54 +02:00
|
|
|
module.exports = RedisDocumentStore;
|