@thermopylae/lib.cache
Version:
85 lines (84 loc) • 2.62 kB
JavaScript
import { EventEmitter } from 'events';
import { NOT_FOUND_VALUE } from "../constants.js";
const POLICIES_SYM = Symbol('POLICIES_SYM');
class PolicyPerKeyCache extends EventEmitter {
backend;
policies;
allPoliciesTags;
constructor(backend, policies) {
super();
this.backend = backend;
this.policies = policies;
this.allPoliciesTags = Array.from(this.policies.keys());
for (const policy of this.policies.values()) {
policy.setDeleter(this.internalDelete);
}
}
get size() {
return this.backend.size;
}
get(key) {
const entry = this.backend.get(key);
if (entry === NOT_FOUND_VALUE) {
for (const policy of this.policies.values()) {
policy.onMiss(key);
}
return entry;
}
for (const policyName of entry[POLICIES_SYM]) {
if (this.policies.get(policyName).onHit(entry) === 0 ) {
return NOT_FOUND_VALUE;
}
}
return entry.value;
}
set(key, value, argsBundle) {
let entry = this.backend.get(key);
if (entry === NOT_FOUND_VALUE) {
entry = this.backend.set(key, value);
entry[POLICIES_SYM] = argsBundle && argsBundle.policies ? argsBundle.policies : this.allPoliciesTags;
for (const policyName of entry[POLICIES_SYM]) {
this.policies.get(policyName).onSet(entry, argsBundle);
}
this.emit("insert" , key, value);
return;
}
entry.value = value;
for (const policyName of entry[POLICIES_SYM]) {
this.policies.get(policyName).onUpdate(entry, argsBundle);
}
this.emit("update" , key, value);
}
has(key) {
return this.backend.has(key);
}
del(key) {
const entry = this.backend.get(key);
if (!entry) {
return false;
}
this.internalDelete(entry);
return true;
}
clear() {
for (const policy of this.policies.values()) {
policy.onClear();
}
this.backend.clear();
this.emit("flush" );
}
keys() {
return Array.from(this.backend.keys());
}
on(event, listener) {
return super.on(event, listener);
}
internalDelete = (entry) => {
for (const policyName of entry[POLICIES_SYM]) {
this.policies.get(policyName).onDelete(entry);
}
this.emit("delete" , entry.key, entry.value);
this.backend.del(entry);
};
}
export { PolicyPerKeyCache };