UNPKG

@jbagatta/johnny-cache

Version:

A robust distributed dictionary for coordinating and caching expensive operations in a distributed environment

36 lines (35 loc) 1.26 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NatsL1CacheManager = void 0; const keyDeletedChannel = (namespace) => `johnny-cache-keydel.${namespace}.*`; const keyDeletedSubject = (namespace, key) => `johnny-cache-keydel.${namespace}.${key}`; class NatsL1CacheManager { constructor(natsClient, namespace, l1Cache) { this.natsClient = natsClient; this.namespace = namespace; this.l1Cache = l1Cache; this.subscription = this.natsClient.subscribe(keyDeletedChannel(this.namespace), { callback: (err, msg) => { const key = msg.subject.split('.')[2]; this.l1Cache.del(key); } }); } get(key) { return this.l1Cache.get(key) ?? null; } set(key, value, ttl) { return ttl ? this.l1Cache.set(key, value, ttl * 0.001) : this.l1Cache.set(key, value); } async delete(key) { this.l1Cache.del(key); this.natsClient.publish(keyDeletedSubject(this.namespace, key), Buffer.from([])); } ttl(key, ttlMs) { this.l1Cache.ttl(key, ttlMs * 0.001); } close() { this.subscription.unsubscribe(); } } exports.NatsL1CacheManager = NatsL1CacheManager;