UNPKG

timed-kvs

Version:

Lightweight Key-value storage with built-in TTL expiration management

62 lines (61 loc) 1.83 kB
"use strict"; /** * timed-kvs.ts */ Object.defineProperty(exports, "__esModule", { value: true }); exports.TimedKVS = void 0; const linked_kvs_1 = require("./linked-kvs"); /** * Storage with TTL for each entries */ class TimedKVS extends linked_kvs_1.LinkedKVS { constructor(options) { super(); const { expires, maxItems } = options || {}; this.expires = (expires > 0) && +expires || 0; this.maxItems = (maxItems > 0) && +maxItems || 0; } getItem(key) { const { expires } = this; const item = super.getItem(key); if (!item) return; if (expires) { const now = Date.now(); // if the cached item is expired, remove rest of items as expired as well. if (now > item.ttl) { this.truncate(item); return; } } return item; } setItem(key, item) { const { expires, maxItems } = this; if (expires) { if (this.firstKey) { // check the first item expired or not const expired = !this.getItem(this.firstKey); if (expired) this.firstKey = undefined; } else { this.firstKey = key; } const now = Date.now(); item.ttl = now + expires; } super.setItem(key, item); if (maxItems) { if (this.gcTimeout || maxItems >= this.size()) return; const gcDelay = Math.min(maxItems, 1000); // garbage collection in background this.gcTimeout = setTimeout(() => { this.shrink(maxItems); delete this.gcTimeout; }, gcDelay); } } } exports.TimedKVS = TimedKVS;