cache categories:cid and cid:<cid>:children

these rarely change, no need to go to db for them
This commit is contained in:
Barış Soner Uşaklı
2018-11-27 19:38:28 -05:00
parent 7357926fe7
commit 00a066985a
15 changed files with 168 additions and 43 deletions

56
src/cache.js Normal file
View File

@@ -0,0 +1,56 @@
'use strict';
var LRU = require('lru-cache');
var pubsub = require('./pubsub');
var cache = LRU({
max: 1000,
maxAge: 0,
});
cache.hits = 0;
cache.misses = 0;
const cacheGet = cache.get;
const cacheDel = cache.del;
const cacheReset = cache.reset;
cache.get = function (key) {
const data = cacheGet.apply(cache, [key]);
if (data === undefined) {
cache.misses += 1;
} else {
cache.hits += 1;
}
return data;
};
cache.del = function (key) {
if (!Array.isArray(key)) {
key = [key];
}
pubsub.publish('local:cache:del', key);
key.forEach(key => cacheDel.apply(cache, [key]));
};
cache.reset = function () {
pubsub.publish('local:cache:reset');
localReset();
};
function localReset() {
cacheReset.apply(cache);
cache.hits = 0;
cache.misses = 0;
}
pubsub.on('local:cache:reset', function () {
localReset();
});
pubsub.on('local:cache:del', function (keys) {
if (Array.isArray(keys)) {
keys.forEach(key => cacheDel.apply(cache, [key]));
}
});
module.exports = cache;