steplix-cache
Version:
Steplix Cache is a Node.js cache helper.
143 lines (119 loc) • 3.34 kB
JavaScript
'use strict';
const _ = require('lodash');
const P = require('bluebird');
const redis = require('redis');
const Base = require('./abstract');
const host = process.env.CACHE_HOST || 'localhost';
const port = process.env.CACHE_PORT || 6379;
const preventError = process.env.CACHE_PREVENT_ERROR || false;
P.promisifyAll(redis.RedisClient.prototype);
P.promisifyAll(redis.Multi.prototype);
class Cache extends Base {
constructor () {
super();
if (this.isEnabled) {
this.client = redis.createClient(_.defaults({}, { host, port }));
this.client.on('connect', () => {
this.isEnabled = true;
console.log('Successfully connected to redis');
});
if (preventError) {
this.client.on('error', (error) => {
this.isEnabled = false;
console.error(error.message);
});
}
}
}
get (key, defaultValue) {
if (!this.isEnabled) {
return P.resolve(defaultValue);
}
return this.client.getAsync(key).then(value => {
if (!_.isNil(value)) {
return JSON.parse(value);
}
return defaultValue;
});
}
put (key, value, time) {
if (!this.isEnabled) {
return P.resolve(value);
}
if (_.isObject(key)) {
time = value;
}
if (!_.isObject(key)) {
if (_.isNil(value)) {
return this.remove(key);
}
else {
key = {
[key]: value
};
}
}
let p = P.bind(this);
_.each(key, (v, k) => {
p = p.then(() => {
if (time) return this.client.setAsync(k, JSON.stringify(v), 'PX', time);
return this.client.setAsync(k, JSON.stringify(v));
});
});
return p.then(() => {
return value;
});
}
remove (keys) {
if (!this.isEnabled) {
return P.resolve();
}
return this.client.delAsync(_.isArray(keys) ? keys : [keys]);
}
removeMatch (pattern) {
if (!this.isEnabled) {
return P.resolve();
}
return this.client.keysAsync(pattern).then(keys => {
if (!keys || !keys.length) {
return keys;
}
return this.remove(keys);
});
}
clear () {
return this.removeMatch('*');
}
configure (options) {
if (this.isEnabled) {
_.extend(this.client.options, options || {});
}
}
end (flush) {
if (!this.isEnabled) {
return P.resolve();
}
return new P((resolve, reject) => {
try {
this.client.endAsync(flush).then(resolve);
}
catch (e) {
reject(e);
}
});
}
quit () {
if (!this.isEnabled) {
return P.resolve();
}
return new P((resolve, reject) => {
try {
this.client.quit(resolve);
}
catch (e) {
reject(e);
}
});
}
}
module.exports = Cache;