Spaces:
Sleeping
Sleeping
File size: 1,660 Bytes
3cd9260 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | /**
* lib/cache.js
*
* Simple in-memory cache with TTL (Time-To-Live) support.
* Date-keyed so each day gets its own cache slot.
*/
class Cache {
constructor() {
this._store = new Map();
this._timestamps = new Map();
this._defaultTTL = 6 * 60 * 60 * 1000; // 6 hours in ms
}
/**
* Get a cached value. Returns null if expired or missing.
*/
get(key) {
const entry = this._store.get(key);
const timestamp = this._timestamps.get(key);
if (!entry || !timestamp) return null;
const age = Date.now() - timestamp;
if (age > this._defaultTTL) {
this._store.delete(key);
this._timestamps.delete(key);
return null;
}
return entry;
}
/**
* Store a value in the cache.
*/
set(key, value) {
this._store.set(key, value);
this._timestamps.set(key, Date.now());
}
/**
* Set the default TTL in milliseconds.
*/
setTTL(milliseconds) {
this._defaultTTL = milliseconds;
}
/**
* Clear ALL cache entries.
*/
clearAll() {
this._store.clear();
this._timestamps.clear();
console.log("[Cache] All entries cleared.");
}
/**
* Clear entries matching a pattern.
*/
clearByPrefix(prefix) {
for (const key of this._store.keys()) {
if (key.startsWith(prefix)) {
this._store.delete(key);
this._timestamps.delete(key);
}
}
console.log(`[Cache] Entries with prefix "${prefix}" cleared.`);
}
/**
* Get cache stats.
*/
stats() {
return {
entries: this._store.size,
keys: Array.from(this._store.keys()),
};
}
}
// Export as singleton
module.exports = new Cache(); |