UNPKG

@vendure/core

Version:

A modern, headless ecommerce framework

63 lines 1.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TtlCache = void 0; /** * @description * An in-memory cache with a configurable TTL (time to live) which means cache items * expire after they have been in the cache longer than that time. * * The `ttl` config option is in milliseconds. Defaults to 30 seconds TTL and a cache size of 1000. * * @deprecated Use the CacheService instead */ class TtlCache { constructor(config) { this.cache = new Map(); this.ttl = 30 * 1000; this.cacheSize = 1000; if (config === null || config === void 0 ? void 0 : config.ttl) { this.ttl = config.ttl; } if (config === null || config === void 0 ? void 0 : config.cacheSize) { this.cacheSize = config.cacheSize; } } get(key) { const hit = this.cache.get(key); const now = new Date().getTime(); if (hit) { if (now < hit.expires) { return hit.value; } else { this.cache.delete(key); } } } set(key, value) { if (this.cache.has(key)) { // delete key to put the item to the end of // the cache, marking it as new again this.cache.delete(key); } else if (this.cache.size === this.cacheSize) { // evict oldest const oldest = this.first(); if (oldest) { this.cache.delete(oldest); } } this.cache.set(key, { value, expires: new Date().getTime() + this.ttl, }); } delete(key) { this.cache.delete(key); } first() { return this.cache.keys().next().value; } } exports.TtlCache = TtlCache; //# sourceMappingURL=ttl-cache.js.map