UNPKG

@varasto/cache-storage

Version:

Varasto storage implementation that acts as cache for another storage

59 lines (58 loc) 1.61 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NamespaceCache = exports.Cache = void 0; const isExpired = (entry) => entry.expires != null && Date.now() >= entry.expires; /** * Simple map based cache implementation with TTL. */ class Cache { constructor(ttl) { this.ttl = ttl; this.storage = new Map(); } get isEmpty() { return this.storage.size === 0; } get(key) { const entry = this.storage.get(key); return entry != null && !isExpired(entry) ? entry.value : undefined; } set(key, value) { this.storage.set(key, { expires: this.ttl != null ? Date.now() + this.ttl : undefined, value, }); } delete(key) { this.storage.delete(key); } } exports.Cache = Cache; class NamespaceCache { constructor(ttl) { this.ttl = ttl; this.storage = new Map(); } get(namespace, key) { var _a; return (_a = this.storage.get(namespace)) === null || _a === void 0 ? void 0 : _a.get(key); } set(namespace, key, value) { let cache = this.storage.get(namespace); if (!cache) { cache = new Cache(this.ttl); this.storage.set(namespace, cache); } cache.set(key, value); } delete(namespace, key) { const cache = this.storage.get(namespace); if (cache) { cache.delete(key); if (cache.isEmpty) { this.storage.delete(namespace); } } } } exports.NamespaceCache = NamespaceCache;