@jbagatta/johnny-cache
Version:
A robust distributed dictionary for coordinating and caching expensive operations in a distributed environment
41 lines (40 loc) • 1.34 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisL1CacheManager = void 0;
const keyDeletedChannel = (namespace) => `johnny-cache-keydel:${namespace}`;
class RedisL1CacheManager {
constructor(redis, namespace, l1Cache) {
this.redis = redis;
this.namespace = namespace;
this.l1Cache = l1Cache;
this.subscriber = this.redis.duplicate();
this.subscriber.subscribe(keyDeletedChannel(this.namespace));
this.subscriber.on('message', (channel, message) => {
try {
const key = message;
l1Cache.del(key);
}
catch (error) {
console.error(error);
}
});
}
get(key) {
return this.l1Cache.get(key) ?? null;
}
set(key, value, ttl) {
return ttl ? this.l1Cache.set(key, value, ttl) : this.l1Cache.set(key, value);
}
async delete(key) {
this.l1Cache.del(key);
await this.redis.publish(keyDeletedChannel(this.namespace), key);
}
ttl(key, ttlMs) {
this.l1Cache.ttl(key, ttlMs * 0.001);
}
close() {
this.subscriber.unsubscribe(keyDeletedChannel(this.namespace));
this.subscriber.quit().catch(console.error);
}
}
exports.RedisL1CacheManager = RedisL1CacheManager;