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-01 23:43:54 +02:00
|
|
|
async set(key, data, callback, skipExpire){
|
|
|
|
await this.client.set(key, data).catch(err => {
|
|
|
|
winston.error('failed to call redisClient.set', {error: err});
|
|
|
|
callback(false);
|
|
|
|
return;
|
|
|
|
});
|
|
|
|
if (!skipExpire) this.setExpiration(key);
|
|
|
|
callback(true);
|
2020-08-28 04:39:03 +02:00
|
|
|
}
|
2018-09-19 16:37:34 +02:00
|
|
|
|
2020-09-01 23:43:54 +02:00
|
|
|
async get(key, callback, skipExpire){
|
|
|
|
let data = await this.client.get(key).catch(err => {
|
|
|
|
winston.error('failed to get document from redis', {key: key, error: err});
|
2020-08-28 04:39:03 +02:00
|
|
|
callback(false);
|
2020-09-01 23:43:54 +02:00
|
|
|
return;
|
2020-08-28 04:39:03 +02:00
|
|
|
});
|
2020-09-01 23:43:54 +02:00
|
|
|
if (!skipExpire) this.setExpiration(key);
|
|
|
|
callback(data);
|
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 => {
|
|
|
|
winston.warn('failed to set expiry on key', {key: key, error: err});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2011-11-19 01:52:18 +01:00
|
|
|
|
2020-09-01 23:43:54 +02:00
|
|
|
module.exports = RedisDocumentStore;
|