Add in-memory caching strategy for aggregated queries with TTL and automatic invalidation on data changes

This commit is contained in:
nmemmert committed 2025-12-11 09:54:19 -05:00
1 parent a4206b9a0f
commit a4295d8081
4 files changed
+110 -5

No files matched your search

+54
View File
@@ -0,0 +1,54 @@
// Simple in-memory cache with TTL support
class CacheManager {
constructor() {
this.cache = new Map();
}
set(key, value, ttlSeconds = 300) {
const expiresAt = Date.now() + (ttlSeconds * 1000);
this.cache.set(key, { value, expiresAt });
}
get(key) {
const item = this.cache.get(key);
if (!item) return null;
if (Date.now() > item.expiresAt) {
this.cache.delete(key);
return null;
}
return item.value;
}
has(key) {
return this.get(key) !== null;
}
delete(key) {
this.cache.delete(key);
}
clear() {
this.cache.clear();
}
// Invalidate all cache keys matching a pattern
invalidatePattern(pattern) {
for (const key of this.cache.keys()) {
if (key.includes(pattern)) {
this.cache.delete(key);
}
}
}
// Get cache statistics
getStats() {
return {
size: this.cache.size,
keys: Array.from(this.cache.keys()),
};
}
}
module.exports = new CacheManager();