@acuris/leprechaun-cache
Version:
Caching library that supports double checked caching and stale returns to avoid stampede and slow responses
50 lines • 1.43 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const uuid = require("uuid");
class MemoryCacheStore {
constructor() {
this.items = new Map();
this.locks = new Map();
}
get(key) {
const item = this.items.get(key);
if (item && item.ttl >= Date.now()) {
return Promise.resolve(item.data);
}
return Promise.resolve(null);
}
set(key, data, ttl) {
this.items.set(key, {
data,
ttl: Date.now() + ttl
});
return Promise.resolve(true);
}
del(key) {
this.items.delete(key);
return Promise.resolve(true);
}
lock(key, ttl) {
const lock = this.locks.get(key);
if (lock && lock.ttl >= Date.now()) {
return Promise.resolve(false);
}
const lockId = uuid.v4();
this.locks.set(key, { ttl: Date.now() + ttl, id: lockId });
return Promise.resolve(lockId);
}
unlock(key, lockId) {
const lock = this.locks.get(key);
if (lock && lock.ttl >= Date.now() && lock.id !== lockId) {
return Promise.resolve(false);
}
this.locks.delete(key);
return Promise.resolve(true);
}
reset() {
this.items = new Map();
this.locks = new Map();
}
}
exports.MemoryCacheStore = MemoryCacheStore;
//# sourceMappingURL=memory-cache-store.js.map