2021-09-21 09:58:22 -07:00
|
|
|
function MemoryCache() {
|
|
|
|
this.cache = {};
|
|
|
|
this.size = 0;
|
|
|
|
}
|
|
|
|
|
2022-04-21 11:55:01 -07:00
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param {string} key Key to store cache as
|
|
|
|
* @param {any} value Value to store
|
|
|
|
* @param {number} time Time to store for
|
|
|
|
* @param {function(any, string)} timeoutCallback Callback to call in
|
|
|
|
* case of timeout
|
|
|
|
* @returns {Object}
|
|
|
|
*/
|
2021-09-21 09:58:22 -07:00
|
|
|
MemoryCache.prototype.add = function (key, value, time, timeoutCallback) {
|
|
|
|
let old = this.cache[key];
|
|
|
|
let instance = this;
|
|
|
|
|
|
|
|
let entry = {
|
|
|
|
value: value,
|
|
|
|
expire: time + Date.now(),
|
|
|
|
timeout: setTimeout(function () {
|
|
|
|
instance.delete(key);
|
|
|
|
return timeoutCallback && typeof timeoutCallback === "function" && timeoutCallback(value, key);
|
|
|
|
}, time)
|
|
|
|
};
|
|
|
|
|
|
|
|
this.cache[key] = entry;
|
|
|
|
this.size = Object.keys(this.cache).length;
|
|
|
|
|
|
|
|
return entry;
|
|
|
|
};
|
|
|
|
|
2022-04-21 11:55:01 -07:00
|
|
|
/**
|
|
|
|
* Delete a cache entry
|
|
|
|
* @param {string} key Key to delete
|
|
|
|
* @returns {null}
|
|
|
|
*/
|
2021-09-21 09:58:22 -07:00
|
|
|
MemoryCache.prototype.delete = function (key) {
|
|
|
|
let entry = this.cache[key];
|
|
|
|
|
|
|
|
if (entry) {
|
|
|
|
clearTimeout(entry.timeout);
|
|
|
|
}
|
|
|
|
|
|
|
|
delete this.cache[key];
|
|
|
|
|
|
|
|
this.size = Object.keys(this.cache).length;
|
|
|
|
|
|
|
|
return null;
|
|
|
|
};
|
|
|
|
|
2022-04-21 11:55:01 -07:00
|
|
|
/**
|
|
|
|
* Get value of key
|
|
|
|
* @param {string} key
|
|
|
|
* @returns {Object}
|
|
|
|
*/
|
2021-09-21 09:58:22 -07:00
|
|
|
MemoryCache.prototype.get = function (key) {
|
|
|
|
let entry = this.cache[key];
|
|
|
|
|
|
|
|
return entry;
|
|
|
|
};
|
|
|
|
|
2022-04-21 11:55:01 -07:00
|
|
|
/**
|
|
|
|
* Get value of cache entry
|
|
|
|
* @param {string} key
|
|
|
|
* @returns {any}
|
|
|
|
*/
|
2021-09-21 09:58:22 -07:00
|
|
|
MemoryCache.prototype.getValue = function (key) {
|
|
|
|
let entry = this.get(key);
|
|
|
|
|
|
|
|
return entry && entry.value;
|
|
|
|
};
|
|
|
|
|
2022-04-21 11:55:01 -07:00
|
|
|
/**
|
|
|
|
* Clear cache
|
|
|
|
* @returns {boolean}
|
|
|
|
*/
|
2021-09-21 09:58:22 -07:00
|
|
|
MemoryCache.prototype.clear = function () {
|
|
|
|
Object.keys(this.cache).forEach(function (key) {
|
|
|
|
this.delete(key);
|
|
|
|
}, this);
|
|
|
|
|
|
|
|
return true;
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = MemoryCache;
|