@amirmarmul/waba-common
Version:

63 lines (62 loc) • 1.86 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.InMemoryCache = void 0;
const DEFAULT_TTL_IN_SECONDS = 30; // seconds
/**
* @deprecated
*/
class InMemoryCache {
TTL;
store = new Map();
timeoutRefs = new Map();
constructor() {
this.TTL = DEFAULT_TTL_IN_SECONDS;
}
async get(key) {
const now = Date.now();
const record = this.store.get(key);
const expiration = record?.expire ?? Infinity;
if (!record || expiration < now) {
return null;
}
return record.data;
}
async set(key, data, ttl = this.TTL) {
if (ttl === 0) {
return;
}
const record = { data, expire: ttl * 1000 + Date.now() };
const oldRecord = this.store.get(key);
if (oldRecord) {
clearTimeout(this.timeoutRefs.get(key));
this.timeoutRefs.delete(key);
}
const ref = setTimeout(async () => {
await this.invalidate(key);
}, ttl * 1000);
ref.unref();
this.timeoutRefs.set(key, ref);
this.store.set(key, record);
}
async invalidate(key) {
let keys = [key];
if (key.includes("*")) {
const regExp = new RegExp(key.replace("*", ".*"));
keys = Array.from(this.store.keys()).filter((k) => k.match(regExp));
}
keys.forEach((key) => {
const timeoutRef = this.timeoutRefs.get(key);
if (timeoutRef) {
clearTimeout(timeoutRef);
this.timeoutRefs.delete(key);
}
this.store.delete(key);
});
}
async clear() {
this.timeoutRefs.forEach((ref) => clearTimeout(ref));
this.timeoutRefs.clear();
this.store.clear();
}
}
exports.InMemoryCache = InMemoryCache;