UNPKG

magicbell

Version:
56 lines 1.78 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Cache = void 0; const log_js_1 = require("./log.js"); function sortObj(obj) { const entries = Object.entries(obj || {}); if (entries.length === 0) return undefined; return Object.fromEntries(entries.sort()); } class Cache { #records = new Map(); #ttl; constructor(options) { this.#ttl = options?.ttl ?? 1000; } getRequestKey(args) { const { method, url, data, headers } = args; return JSON.stringify({ method, url: url.toString(), data: sortObj(data), headers: sortObj(headers), }); } #flush() { const currentTimestamp = Date.now(); for (const [key, { timestamp }] of this.#records.entries()) { if (currentTimestamp - timestamp >= this.#ttl) { const age = currentTimestamp - timestamp; (0, log_js_1.debug)('cache FLUSH', { key, age, ttl: this.#ttl }); this.#records.delete(key); } } } get(key) { this.#flush(); const record = this.#records.get(key); if (record) { const age = Date.now() - record.timestamp; (0, log_js_1.debug)('cache HIT', { key, age, ttl: this.#ttl }); return record.promise; } (0, log_js_1.debug)('cache MISS', { key, ttl: this.#ttl }); return null; } set(key, promise) { if (this.#ttl <= 0) return; const timestamp = Date.now(); (0, log_js_1.debug)('cache SET', { key, timestamp, ttl: this.#ttl }); this.#records.set(key, { promise, timestamp }); } } exports.Cache = Cache; //# sourceMappingURL=cache.js.map