@hokify/node-ts-cache-lru-redis-storage
Version:
Simple and extensible caching module supporting decorators
53 lines • 1.76 kB
JavaScript
import LRU from 'lru-cache';
export class LRUWithRedisStorage {
constructor(options, redis) {
this.redis = redis;
this.options = {
max: 500,
maxAge: 86400,
...options
};
this.myCache = new LRU({
...this.options,
maxAge: (this.options.maxAge || 86400) * 1000 // in ms
});
}
async getItem(key) {
// check local cache
let localCache = this.myCache.get(key);
if (localCache === undefined) {
// check central cache
localCache = await this.redis().get(key);
if (localCache !== undefined) {
try {
localCache = JSON.parse(localCache);
}
catch (err) {
console.error('lru redis cache failed parsing data', err);
localCache = undefined;
}
// if found on central cache, copy it to a local cache
this.myCache.set(key, localCache);
}
}
return localCache ?? undefined;
}
/** ttl in seconds! */
async setItem(key, content, options) {
this.myCache.set(key, content);
if (this.options?.maxAge) {
await this.redis().setex(key, options?.ttl || this.options.maxAge, JSON.stringify(content));
}
else {
await this.redis().set(key, JSON.stringify(content));
}
}
async clear() {
// flush not supported, recreate local lru cache instance
this.myCache = new LRU({
...this.options,
maxAge: (this.options.maxAge || 86400) * 1000 // in ms
});
}
}
//# sourceMappingURL=LRUWithRedisStorage.js.map