UNPKG

@linkedmink/multilevel-aging-cache

Version:

Package provides an interface to cache and persist data to Redis, MongoDB, memory

69 lines (68 loc) 2.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AgingCacheWriteStrategy = void 0; const Logger_1 = require("../shared/Logger"); const IAgingCache_1 = require("./IAgingCache"); /** * Keep common methods and data for each set/delete strategy here */ class AgingCacheWriteStrategy { /** * @param hierarchy The storage hierarchy to operate on * @param evictQueue The keys in the order to evict */ constructor(hierarchy, evictQueue) { this.hierarchy = hierarchy; this.evictQueue = evictQueue; this.logger = Logger_1.Logger.get(AgingCacheWriteStrategy.name); this.executeDelete = (key, level) => { return this.hierarchy.deleteAtLevel(key, level).then(status => { const write = this.getWriteStatus(status, level); if (write.status === IAgingCache_1.AgingCacheWriteStatus.Success) { this.evictQueue.delete(key); } return write; }); }; this.executeSet = (key, value, level) => { const agedValue = { age: this.evictQueue.getInitialAge(key), value, }; return this.hierarchy.setAtLevel(key, agedValue, level).then(status => { const write = this.getWriteStatus(status, level); if (write.status === IAgingCache_1.AgingCacheWriteStatus.Success) { this.evictQueue.addOrReplace(key, agedValue.age); } return write; }); }; this.setFromHighestLevel = (key, agedValue) => { return this.hierarchy.setBelowTopLevel(key, agedValue).then(status => { if (status.writtenLevels === this.hierarchy.totalLevels - 1) { this.evictQueue.addOrReplace(key, agedValue.age); return Promise.resolve({ status: IAgingCache_1.AgingCacheWriteStatus.Refreshed, value: status.writtenValue?.value, }); } return Promise.resolve({ status: IAgingCache_1.AgingCacheWriteStatus.RefreshedError, value: status.writtenValue?.value, }); }); }; } getWriteStatus(status, level) { const expectedWritten = level ? level + 1 : this.hierarchy.totalLevels; return { status: status.writtenLevels === expectedWritten ? IAgingCache_1.AgingCacheWriteStatus.Success : status.writtenLevels === 0 ? IAgingCache_1.AgingCacheWriteStatus.UnspecifiedError : IAgingCache_1.AgingCacheWriteStatus.PartialWrite, value: status.writtenValue?.value, }; } } exports.AgingCacheWriteStrategy = AgingCacheWriteStrategy;