mirror of
https://github.com/NodeBB/NodeBB.git
synced 2025-10-26 16:46:12 +01:00
* feat: #8824, cache refactor ability to disable caches ability to download contents of cache refactor cache modules to remove duplicated code * fix: remove duplicate hit/miss tracking check cacheEnabled in getUncachedKeys
This commit is contained in:
committed by
GitHub
parent
bcbc085497
commit
f1f9b225b0
91
src/cacheCreate.js
Normal file
91
src/cacheCreate.js
Normal file
@@ -0,0 +1,91 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = function (opts) {
|
||||
const LRU = require('lru-cache');
|
||||
const pubsub = require('./pubsub');
|
||||
|
||||
const cache = new LRU(opts);
|
||||
|
||||
cache.name = opts.name;
|
||||
cache.hits = 0;
|
||||
cache.misses = 0;
|
||||
cache.enabled = opts.hasOwnProperty('enabled') ? opts.enabled : true;
|
||||
|
||||
const cacheSet = cache.set;
|
||||
const cacheGet = cache.get;
|
||||
const cacheDel = cache.del;
|
||||
const cacheReset = cache.reset;
|
||||
|
||||
cache.set = function (key, value) {
|
||||
if (!cache.enabled) {
|
||||
return;
|
||||
}
|
||||
cacheSet.apply(cache, [key, value]);
|
||||
};
|
||||
|
||||
cache.get = function (key) {
|
||||
if (!cache.enabled) {
|
||||
return undefined;
|
||||
}
|
||||
const data = cacheGet.apply(cache, [key]);
|
||||
if (data === undefined) {
|
||||
cache.misses += 1;
|
||||
} else {
|
||||
cache.hits += 1;
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
cache.del = function (keys) {
|
||||
if (!Array.isArray(keys)) {
|
||||
keys = [keys];
|
||||
}
|
||||
pubsub.publish(cache.name + ':cache:del', keys);
|
||||
keys.forEach(key => cacheDel.apply(cache, [key]));
|
||||
};
|
||||
|
||||
cache.reset = function () {
|
||||
pubsub.publish(cache.name + ':cache:reset');
|
||||
localReset();
|
||||
};
|
||||
|
||||
function localReset() {
|
||||
cacheReset.apply(cache);
|
||||
cache.hits = 0;
|
||||
cache.misses = 0;
|
||||
}
|
||||
|
||||
pubsub.on(cache.name + ':cache:reset', function () {
|
||||
localReset();
|
||||
});
|
||||
|
||||
pubsub.on(cache.name + ':cache:del', function (keys) {
|
||||
if (Array.isArray(keys)) {
|
||||
keys.forEach(key => cacheDel.apply(cache, [key]));
|
||||
}
|
||||
});
|
||||
|
||||
cache.getUnCachedKeys = function (keys, cachedData) {
|
||||
if (!cache.enabled) {
|
||||
return keys;
|
||||
}
|
||||
let data;
|
||||
let isCached;
|
||||
const unCachedKeys = keys.filter(function (key) {
|
||||
data = cache.get(key);
|
||||
isCached = data !== undefined;
|
||||
if (isCached) {
|
||||
cachedData[key] = data;
|
||||
}
|
||||
return !isCached;
|
||||
});
|
||||
|
||||
var hits = keys.length - unCachedKeys.length;
|
||||
var misses = keys.length - hits;
|
||||
cache.hits += hits;
|
||||
cache.misses += misses;
|
||||
return unCachedKeys;
|
||||
};
|
||||
|
||||
return cache;
|
||||
};
|
||||
Reference in New Issue
Block a user