Chaching improvements
This commit is contained in:
54
src/utils/cacheManager.js
Normal file
54
src/utils/cacheManager.js
Normal file
@@ -0,0 +1,54 @@
|
||||
const logger = require('../../modules/colorfulLogger');
|
||||
|
||||
class CacheManager {
|
||||
constructor() {
|
||||
this.cache = new Map();
|
||||
logger.info('CacheManager initialized.');
|
||||
}
|
||||
|
||||
get(key) {
|
||||
const cachedItem = this.cache.get(key);
|
||||
if (!cachedItem) {
|
||||
logger.debug(`Cache MISS for key: ${key}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (cachedItem.expire && Date.now() > cachedItem.expire) {
|
||||
logger.info(`Cache EXPIRED for key: ${key}`);
|
||||
this.cache.delete(key);
|
||||
return null;
|
||||
}
|
||||
|
||||
logger.debug(`Cache HIT for key: ${key}`);
|
||||
return cachedItem.value;
|
||||
}
|
||||
|
||||
set(key, value, ttl = 0) {
|
||||
logger.debug(`Caching data for key: ${key} with TTL: ${ttl}ms`);
|
||||
this.cache.set(key, {
|
||||
value: value,
|
||||
expire: ttl > 0 ? Date.now() + ttl : null,
|
||||
});
|
||||
}
|
||||
|
||||
has(key) {
|
||||
return this.cache.has(key);
|
||||
}
|
||||
|
||||
delete(key) {
|
||||
logger.debug(`Deleting cache for key: ${key}`);
|
||||
return this.cache.delete(key);
|
||||
}
|
||||
|
||||
flush() {
|
||||
logger.info('Flushing all caches.');
|
||||
this.cache.clear();
|
||||
}
|
||||
|
||||
get size() {
|
||||
return this.cache.size;
|
||||
}
|
||||
}
|
||||
|
||||
const cacheManager = new CacheManager();
|
||||
module.exports = cacheManager;
|
Reference in New Issue
Block a user