veas
Version:
Veas CLI - Command-line interface for Veas platform
101 lines • 2.57 kB
JavaScript
import NodeCache from 'node-cache';
export class CacheManager {
static instance = null;
cache;
enabled;
constructor(options) {
this.enabled = options?.enabled ?? true;
this.cache = new NodeCache({
stdTTL: options?.ttl ?? 3600,
checkperiod: 120,
});
}
static getInstance(options) {
if (!CacheManager.instance) {
CacheManager.instance = new CacheManager(options);
}
return CacheManager.instance;
}
get(key, params) {
if (!this.enabled)
return undefined;
const cacheKey = this.createKey(key, params);
return this.cache.get(cacheKey);
}
async getAsync(key, params) {
return this.get(key, params);
}
set(key, value, ttl) {
if (!this.enabled)
return false;
if (ttl !== undefined) {
return this.cache.set(key, value, ttl);
}
else {
return this.cache.set(key, value);
}
}
setWithParams(key, params, value, ttl) {
if (!this.enabled)
return false;
const cacheKey = this.createKey(key, params);
if (ttl !== undefined) {
return this.cache.set(cacheKey, value, ttl);
}
else {
return this.cache.set(cacheKey, value);
}
}
async setAsync(key, value, ttl) {
return this.set(key, value, ttl);
}
createKey(key, params) {
if (!params)
return key;
const sortedParams = Object.keys(params)
.sort()
.reduce((acc, k) => {
acc[k] = params[k];
return acc;
}, {});
return `${key}:${JSON.stringify(sortedParams)}`;
}
delete(key) {
if (!this.enabled)
return 0;
return this.cache.del(key);
}
clear() {
this.cache.flushAll();
}
has(key) {
if (!this.enabled)
return false;
return this.cache.has(key);
}
keys() {
if (!this.enabled)
return [];
return this.cache.keys();
}
getTtl(key) {
if (!this.enabled)
return undefined;
return this.cache.getTtl(key);
}
setTtl(key, ttl) {
if (!this.enabled)
return false;
return this.cache.ttl(key, ttl);
}
close() {
this.cache.close();
}
getStats() {
return this.cache.getStats();
}
flush() {
this.cache.flushAll();
}
}
//# sourceMappingURL=cache-manager.js.map