redis-plus-lru-cache
Version:
LRU Cache & Redis Middleware
87 lines (78 loc) • 2.82 kB
JavaScript
var LRU = require("lru-cache");
var redis = require("redis");
var jsonify = require('redis-jsonify');
var lrucache;
var client;
//lrucache.reset();
var x = function (options) {
console.log("options.flag",options.flag)
if(options.flag){
lrucache = LRU(options.lruCache);
client = jsonify(redis.createClient(options.redis.port, options.redis.servers, {}));
if(options.hasOwnProperty('prefix'))
prefix = options.prefix
else
prefix = ""
return {
get: function (key, callback) {
var error = null;
if (lrucache.has(prefix + key)) {
return callback(error, lrucache.get(prefix + key));
} else {
client.get(prefix + key, function (error, data) {
if (data) {
lrucache.set(prefix + key, data);
return callback(error, data);
} else {
return callback(error, null);
}
});
}
},
set: function (key, data,callback) {
lrucache.set(prefix + key, data);
client.set(prefix + key, data, function () {
if (typeof callback == "function")
callback();
});
},
flushLRUCache:function(){
lrucache.reset();
},
flushRedis: function(){
client.send_command("FLUSHALL", null, function(){
console.log("Redis Flushed")
})
},
flushAll: function(){
lrucache.reset();
client.send_command("FLUSHALL", [], function(){
console.log("Redis Flushed")
})
},
flushByPrefix: function(delPrefix){
//client.send_command("COMMAND GETKEYS",["SET"],function(keys){
// console.log(keys+"key")
//})
lrucache.forEach(function(value,key,cache){
if(key.indexOf(delPrefix) == 0 )
lrucache.del( key)
})
}
}
} else {
console.log("blank")
return {
get: function (key, callback) {
var error = null;
return callback(error, null);
},
set: function (key, data,callback) {
var error = null;
if (typeof callback == "function")
callback();
}
}
}
};
module.exports = x