asynchronous-cache
Version:
Simple asynchronous in-memory cache
39 lines (38 loc) • 1.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cache = void 0;
class Cache {
constructor() {
this.cache = new Map();
this.tempCache = new Map();
}
async executeWithCache(key, func, options = {}) {
if (typeof key !== 'string')
throw new Error(`Key should be a string, got ${typeof key}`);
if (this.cache.has(key)) {
return this.cache.get(key);
}
if (this.tempCache.has(key)) {
return await this.tempCache.get(key);
}
if (options.TTL) {
this.deleteWithDelay(key, options.TTL);
}
this.tempCache.set(key, func());
const result = await this.tempCache.get(key);
this.cache.set(key, result);
this.tempCache.delete(key);
return result;
}
delete(key) {
return this.cache.delete(key) || this.tempCache.delete(key);
}
clear() {
this.tempCache.clear();
this.cache.clear();
}
deleteWithDelay(key, delay) {
setTimeout(() => this.delete(key), delay);
}
}
exports.Cache = Cache;