UNPKG

adonis5-cache

Version:
55 lines (54 loc) 2.16 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const dayjs_1 = __importDefault(require("dayjs")); const ramda_1 = require("ramda"); const TypeGuards_1 = require("./TypeGuards"); class TaggableCacheManager { constructor(cacheManager, _tags) { this.cacheManager = cacheManager; this._tags = _tags; if (TypeGuards_1.isTaggableStorage(cacheManager.storage)) { this.storage = cacheManager.storage; } } get tags() { return this._tags; } set tags(value) { this._tags = value; } async flush() { const tagsPayload = await Promise.all(this._tags.map((tag) => this.storage.readTag(this.buildTagKey(tag)))); const keyForRemove = ramda_1.flatten(tagsPayload).reduce((acc, tagContent) => { const obj = JSON.parse(tagContent); if (TypeGuards_1.isTagPayloadContract(obj) && dayjs_1.default().isBefore(dayjs_1.default(obj.expirationTime))) { acc.push(...obj.keys); } return acc; }, []); await Promise.all(keyForRemove.map((key) => this.cacheManager.forget(key))); await Promise.all(this._tags.map((tag) => this.storage.removeTag(this.buildTagKey(tag)))); } async put(key, value, ttl) { await this.saveTaggedKeys([key], ttl); return this.cacheManager.put(key, value, ttl); } async putMany(cacheDictionary, ttl) { await this.saveTaggedKeys(Object.keys(cacheDictionary), ttl); return this.cacheManager.putMany(cacheDictionary, ttl); } async saveTaggedKeys(keys, ttl = this.cacheManager.recordTTL) { const tagPayload = JSON.stringify({ expirationTime: dayjs_1.default().add(ttl, 'ms').toISOString(), keys, }); await Promise.all(this._tags.map((tag) => this.storage.addTag(this.buildTagKey(tag), tagPayload))); } buildTagKey(tag) { return `tag_${tag}`; } } exports.default = TaggableCacheManager;