1
0
Fork 0
mirror of https://github.com/SunRed/haste-server.git synced 2024-11-01 09:40:21 +01:00
haste-server/lib/document_stores/redis.js

53 lines
1.3 KiB
JavaScript
Raw Normal View History

const Redis = require('ioredis');
2020-08-26 04:54:58 +02:00
const winston = require('winston');
2011-11-19 01:52:18 +01:00
class RedisDocumentStore {
2011-11-22 04:03:50 +01: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
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
}
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
async setExpiration(key){
if (!this.expire) return;
await this.client.expire(key, this.expire).catch(err => {
winston.warn('failed to set redis key expiry', {key: key, error: err});
});
}
}
2011-11-19 01:52:18 +01:00
module.exports = RedisDocumentStore;