UNPKG

bentocache

Version:

Multi-tier cache module for Node.js. Redis, Upstash, CloudfareKV, File, in-memory and others drivers

111 lines (110 loc) 2.75 kB
import { BaseDriver } from "../../chunk-BO75WXSS.js"; // src/drivers/memory.ts import { LRUCache } from "lru-cache"; import { bytes } from "@julr/utils/string/bytes"; import { InvalidArgumentsException } from "@poppinss/exception"; function memoryDriver(options = {}) { return { options, factory: (config) => new MemoryDriver(config) }; } var MemoryDriver = class _MemoryDriver extends BaseDriver { type = "l1"; #cache; constructor(config = {}) { super(config); if (config.cacheInstance) { this.#cache = config.cacheInstance; return; } if (config.serialize === false && (config.maxEntrySize || config.maxSize)) { throw new InvalidArgumentsException( "Cannot use maxSize or maxEntrySize when serialize is set to `false`" ); } this.#cache = new LRUCache({ max: config.maxItems ?? 1e3, maxEntrySize: config.maxEntrySize ? bytes.parse(config.maxEntrySize) : void 0, ttlAutopurge: false, ...config.maxSize ? { maxSize: config.maxSize ? bytes.parse(config.maxSize) : void 0, sizeCalculation: (value) => Buffer.byteLength(value, "utf-8") } : {} }); } /** * Returns a new instance of the driver namespaced */ namespace(namespace) { return new _MemoryDriver({ ...this.config, cacheInstance: this.#cache, prefix: this.createNamespacePrefix(namespace) }); } /** * Get a value from the cache */ get(key) { return this.#cache.get(this.getItemKey(key)); } /** * Get the value of a key and delete it * * Returns the value if the key exists, undefined otherwise */ pull(key) { const value = this.get(key); this.delete(key); return value; } /** * Put a value in the cache * Returns true if the value was set, false otherwise */ set(key, value, ttl) { this.#cache.set(this.getItemKey(key), value, { ttl }); return true; } /** * Returns the remaining ttl of a key */ getRemainingTtl(key) { return this.#cache.getRemainingTTL(this.getItemKey(key)); } /** * Remove all items from the cache */ clear() { for (const key of this.#cache.keys()) { if (key.startsWith(`${this.prefix}:`)) { this.#cache.delete(key); } } } /** * Delete a key from the cache * Returns true if the key was deleted, false otherwise */ delete(key) { return this.#cache.delete(this.getItemKey(key)); } /** * Delete multiple keys from the cache */ deleteMany(keys) { if (keys.length === 0) return true; for (const key of keys) this.delete(key); return true; } async disconnect() { } }; export { MemoryDriver, memoryDriver }; //# sourceMappingURL=memory.js.map