@catbee/utils
Version:
A modular, production-grade utility toolkit for Node.js and TypeScript, designed for robust, scalable applications (including Express-based services). All utilities are tree-shakable and can be imported independently.
476 lines • 17.9 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
import { Config } from "../config";
/**
* An in-memory cache with time-to-live (TTL) support for each entry.
*
* @typeParam K - Type of the key.
* @typeParam V - Type of the value.
*
* @example
* const cache = new TTLCache<string, number>({ ttlMs: 1000 });
* cache.set("x", 123);
* const value = cache.get("x"); // 123
*/
var TTLCache = /** @class */ (function () {
/**
* @param options - Configuration options for the cache
*/
function TTLCache(options) {
if (options === void 0) { options = {}; }
var _this = this;
var _a;
this.cache = new Map();
this.ttlMs = (_a = options.ttlMs) !== null && _a !== void 0 ? _a : Config.Cache.defaultTtl;
this.maxSize = options.maxSize;
// Setup auto-cleanup if enabled
var autoCleanupMs = options.autoCleanupMs;
if (autoCleanupMs && autoCleanupMs > 0) {
this.cleanupInterval = setInterval(function () {
_this.cleanup();
}, autoCleanupMs);
}
}
/**
* Sets a key-value pair in the cache with the default TTL.
*
* @param key - The key to set.
* @param value - The value to associate with the key.
*/
TTLCache.prototype.set = function (key, value) {
this.setWithTTL(key, value, this.ttlMs);
};
/**
* Sets a key-value pair in the cache with a custom TTL.
*
* @param key - The key to set.
* @param value - The value to associate with the key.
* @param ttlMs - Time-to-live in milliseconds.
*/
TTLCache.prototype.setWithTTL = function (key, value, ttlMs) {
var now = Date.now();
var expiresAt = now + ttlMs;
this.cache.set(key, { value: value, expiresAt: expiresAt, lastAccessed: now });
// Enforce max size limit if configured
if (this.maxSize && this.cache.size > this.maxSize) {
this.evictLRU();
}
};
/**
* Retrieves the value for a given key if it hasn't expired.
*
* @param key - The key to retrieve.
* @returns The cached value, or undefined if not found or expired.
*/
TTLCache.prototype.get = function (key) {
var entry = this.cache.get(key);
if (!entry)
return undefined;
var now = Date.now();
if (now > entry.expiresAt) {
this.cache.delete(key);
return undefined;
}
// Update last access time for LRU tracking
entry.lastAccessed = now;
return entry.value;
};
/**
* Retrieves or computes a value if it's not in the cache or has expired.
*
* @param key - The key to retrieve
* @param producer - Function to generate the value if not cached
* @param ttlMs - Optional custom TTL for the computed value
* @returns The cached or computed value
*/
TTLCache.prototype.getOrCompute = function (key, producer, ttlMs) {
return __awaiter(this, void 0, void 0, function () {
var value, newValue;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
value = this.get(key);
if (value !== undefined)
return [2 /*return*/, value];
return [4 /*yield*/, producer()];
case 1:
newValue = _a.sent();
this.setWithTTL(key, newValue, ttlMs !== null && ttlMs !== void 0 ? ttlMs : this.ttlMs);
return [2 /*return*/, newValue];
}
});
});
};
/**
* Checks if the key exists and hasn't expired.
*
* @param key - The key to check.
* @returns `true` if key exists and is valid, otherwise `false`.
*/
TTLCache.prototype.has = function (key) {
return this.get(key) !== undefined;
};
/**
* Deletes a key from the cache.
*
* @param key - The key to delete.
* @returns `true` if the key existed and was removed, `false` otherwise.
*/
TTLCache.prototype.delete = function (key) {
return this.cache.delete(key);
};
/**
* Clears all entries from the cache.
*/
TTLCache.prototype.clear = function () {
this.cache.clear();
};
/**
* Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).
*
* @returns Number of items in the cache (may include expired keys).
*/
TTLCache.prototype.size = function () {
return this.cache.size;
};
/**
* Set multiple key-value pairs at once with the default TTL.
*
* @param entries - Array of [key, value] tuples to set
*/
TTLCache.prototype.setMany = function (entries) {
var e_1, _a;
try {
for (var entries_1 = __values(entries), entries_1_1 = entries_1.next(); !entries_1_1.done; entries_1_1 = entries_1.next()) {
var _b = __read(entries_1_1.value, 2), key = _b[0], value = _b[1];
this.set(key, value);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (entries_1_1 && !entries_1_1.done && (_a = entries_1.return)) _a.call(entries_1);
}
finally { if (e_1) throw e_1.error; }
}
};
/**
* Get multiple values at once.
*
* @param keys - Array of keys to retrieve
* @returns Array of values (undefined for keys that don't exist or expired)
*/
TTLCache.prototype.getMany = function (keys) {
var _this = this;
return keys.map(function (key) { return _this.get(key); });
};
/**
* Removes all expired entries from the cache.
*
* @returns Number of entries removed.
*/
TTLCache.prototype.cleanup = function () {
var e_2, _a;
var removed = 0;
var now = Date.now();
try {
for (var _b = __values(this.cache.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
var _d = __read(_c.value, 2), key = _d[0], entry = _d[1];
if (now > entry.expiresAt) {
this.cache.delete(key);
removed++;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_2) throw e_2.error; }
}
return removed;
};
/**
* Returns an iterator of all current valid [key, value] pairs.
*
* @returns IterableIterator<[K, V]>
*/
TTLCache.prototype.entries = function () {
var _a, _b, _c, key, entry, e_3_1;
var e_3, _d;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
_e.trys.push([0, 5, 6, 7]);
_a = __values(this.cache.entries()), _b = _a.next();
_e.label = 1;
case 1:
if (!!_b.done) return [3 /*break*/, 4];
_c = __read(_b.value, 2), key = _c[0], entry = _c[1];
if (!(Date.now() <= entry.expiresAt)) return [3 /*break*/, 3];
return [4 /*yield*/, [key, entry.value]];
case 2:
_e.sent();
_e.label = 3;
case 3:
_b = _a.next();
return [3 /*break*/, 1];
case 4: return [3 /*break*/, 7];
case 5:
e_3_1 = _e.sent();
e_3 = { error: e_3_1 };
return [3 /*break*/, 7];
case 6:
try {
if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
}
finally { if (e_3) throw e_3.error; }
return [7 /*endfinally*/];
case 7: return [2 /*return*/];
}
});
};
/**
* Returns an iterator of all current valid keys.
*
* @returns IterableIterator<K>
*/
TTLCache.prototype.keys = function () {
var _a, _b, _c, key, entry, e_4_1;
var e_4, _d;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
_e.trys.push([0, 5, 6, 7]);
_a = __values(this.cache.entries()), _b = _a.next();
_e.label = 1;
case 1:
if (!!_b.done) return [3 /*break*/, 4];
_c = __read(_b.value, 2), key = _c[0], entry = _c[1];
if (!(Date.now() <= entry.expiresAt)) return [3 /*break*/, 3];
return [4 /*yield*/, key];
case 2:
_e.sent();
_e.label = 3;
case 3:
_b = _a.next();
return [3 /*break*/, 1];
case 4: return [3 /*break*/, 7];
case 5:
e_4_1 = _e.sent();
e_4 = { error: e_4_1 };
return [3 /*break*/, 7];
case 6:
try {
if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
}
finally { if (e_4) throw e_4.error; }
return [7 /*endfinally*/];
case 7: return [2 /*return*/];
}
});
};
/**
* Returns an iterator of all current valid values.
*
* @returns IterableIterator<V>
*/
TTLCache.prototype.values = function () {
var _a, _b, entry, e_5_1;
var e_5, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
_d.trys.push([0, 5, 6, 7]);
_a = __values(this.cache.values()), _b = _a.next();
_d.label = 1;
case 1:
if (!!_b.done) return [3 /*break*/, 4];
entry = _b.value;
if (!(Date.now() <= entry.expiresAt)) return [3 /*break*/, 3];
return [4 /*yield*/, entry.value];
case 2:
_d.sent();
_d.label = 3;
case 3:
_b = _a.next();
return [3 /*break*/, 1];
case 4: return [3 /*break*/, 7];
case 5:
e_5_1 = _d.sent();
e_5 = { error: e_5_1 };
return [3 /*break*/, 7];
case 6:
try {
if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
}
finally { if (e_5) throw e_5.error; }
return [7 /*endfinally*/];
case 7: return [2 /*return*/];
}
});
};
/**
* Extends the expiration of a key by the specified time or default TTL.
*
* @param key - The key to refresh
* @param ttlMs - Optional new TTL in milliseconds (uses default if not specified)
* @returns true if the key was found and refreshed, false otherwise
*/
TTLCache.prototype.refresh = function (key, ttlMs) {
var entry = this.cache.get(key);
if (!entry)
return false;
var now = Date.now();
if (now > entry.expiresAt) {
this.cache.delete(key);
return false;
}
entry.expiresAt = now + (ttlMs !== null && ttlMs !== void 0 ? ttlMs : this.ttlMs);
entry.lastAccessed = now;
return true;
};
/**
* Returns a snapshot of cache stats.
*
* @returns Object containing cache statistics
*/
TTLCache.prototype.stats = function () {
var e_6, _a;
var now = Date.now();
var expired = 0;
var valid = 0;
try {
for (var _b = __values(this.cache.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
var entry = _c.value;
if (now > entry.expiresAt) {
expired++;
}
else {
valid++;
}
}
}
catch (e_6_1) { e_6 = { error: e_6_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_6) throw e_6.error; }
}
return {
size: this.cache.size,
validEntries: valid,
expiredEntries: expired,
maxSize: this.maxSize,
};
};
/**
* Stop the auto-cleanup interval if it's running.
*/
TTLCache.prototype.destroy = function () {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval);
this.cleanupInterval = undefined;
}
};
/**
* Evict the least recently used entry from the cache.
* @private
*/
TTLCache.prototype.evictLRU = function () {
var e_7, _a;
var oldestKey;
var oldestAccess = Infinity;
try {
for (var _b = __values(this.cache.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
var _d = __read(_c.value, 2), key = _d[0], entry = _d[1];
// Skip entries that are already expired
if (Date.now() > entry.expiresAt) {
this.cache.delete(key);
return;
}
// Find the oldest accessed entry
if (entry.lastAccessed && entry.lastAccessed < oldestAccess) {
oldestAccess = entry.lastAccessed;
oldestKey = key;
}
}
}
catch (e_7_1) { e_7 = { error: e_7_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_7) throw e_7.error; }
}
if (oldestKey) {
this.cache.delete(oldestKey);
}
};
return TTLCache;
}());
export { TTLCache };
//# sourceMappingURL=cache.utils.js.map