Add in-memory caching strategy for aggregated queries with TTL and automatic invalidation on data changes
This commit is contained in:
1 parent
a4206b9a0f
commit
a4295d8081
4 files changed
+110
-5
No files matched your search
@@ -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();
|
||||
Reference in new issue
Block a user