UNPKG

@amirmarmul/waba-common

Version:

![GitHub release](https://img.shields.io/github/v/release/amirmarmul/waba-common?style=flat-square)

66 lines (65 loc) 1.93 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ArrayStore = void 0; class ArrayStore { store = new Map(); timeoutRefs = new Map(); 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 put(key, value, ttl) { const record = { data: value, expire: ttl * 1000 + Date.now() }; const oldRecord = this.store.get(key); if (oldRecord) { await this.forget(key); } const ref = setTimeout(async () => { await this.forget(key); }, ttl * 1000); ref.unref(); this.timeoutRefs.set(key, ref); this.store.set(key, record); return true; } async forever(key, value) { const record = { data: value }; const oldRecord = this.store.get(key); if (oldRecord) { await this.forget(key); } this.store.set(key, record); return true; } async forget(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); }); return true; } async flush() { this.timeoutRefs.forEach((ref) => clearTimeout(ref)); this.timeoutRefs.clear(); this.store.clear(); return true; } getPrefix() { return ''; } } exports.ArrayStore = ArrayStore;