@uploadx/core
Version:
Node.js resumable upload middleware
108 lines (107 loc) • 3 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cache = void 0;
/**
* Time-aware LRU Cache Implementation
*/
class Cache {
/**
* @param maxEntries - The maximum number of entries before the cache starts flushing out the old items
* @param maxAge - The maximum life of a cached items in seconds
*/
constructor(maxEntries = 1000, maxAge) {
this.maxEntries = maxEntries;
this.maxAge = maxAge;
this._map = new Map();
this._ttl = maxAge ? maxAge * 1000 : 0;
}
/**
* @returns the total number of cache entries, including expired ones
*/
get size() {
return this._map.size;
}
/**
* Cache keys iterator
* @returns an iterator of all keys in a cache
*/
keys() {
return this._map.keys();
}
/**
* Remove expired entries
* @returns array of actual keys
*/
prune() {
if (this._ttl) {
const now = Date.now();
for (const [key, [, expiresAt]] of this._map) {
if (now > expiresAt)
this._map.delete(key);
}
}
while (this._map.size > this.maxEntries) {
this._map.delete(this._map.keys().next().value);
}
return Array.from(this._map.keys());
}
clear() {
this._map.clear();
}
/**
* Get an item from the cache
* @param key - The key to look up
* @returns The cached value or undefined if it is not found or expired
*/
get(key) {
const tuple = this._map.get(key);
if (!tuple)
return;
this._map.delete(key);
if (this._ttl) {
const now = Date.now();
if (now > tuple[1])
return;
tuple[1] = now + this._ttl;
}
this._map.set(key, tuple);
return tuple[0];
}
/**
* Check if the item exists and has not expired
* @param key - The key to look up
*/
has(key) {
const tuple = this._map.get(key);
if (!tuple)
return false;
if (this._ttl) {
if (Date.now() > tuple[1]) {
this._map.delete(key);
return false;
}
}
return true;
}
/**
* Add the new key and value to the cache
* @param key - The key to store the value under
* @param value - The value to be stored in the cache
* @returns The value that was set
*/
set(key, value) {
if (this._map.size === this.maxEntries)
this._map.delete(this._map.keys().next().value);
const expiresAt = this._ttl ? Date.now() + this._ttl : 0;
this._map.set(key, [value, expiresAt]);
return value;
}
/**
* Delete the key from the cache
* @param key - The key of the item to remove from the cache
*/
delete(key) {
return this._map.delete(key);
}
}
exports.Cache = Cache;