UNPKG

@gabliam/cache

Version:
45 lines (44 loc) 1.94 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CachePut = void 0; const core_1 = require("@gabliam/core"); const cache_options_1 = require("./cache-options"); // eslint-disable-next-line @typescript-eslint/no-redeclare exports.CachePut = (0, core_1.makePropDecorator)('CachePut', (value) => (0, cache_options_1.extractCacheInternalOptions)(value), (target, propertyKey, descriptor, cacheInternalOptions) => { (0, core_1.InjectContainer)()(target.constructor); const method = descriptor.value; let cacheGroup; let cacheConfig; // eslint-disable-next-line no-param-reassign descriptor.value = async function desc(...args) { if (!cacheGroup) { cacheGroup = (0, cache_options_1.getCacheGroup)(target.constructor); } if (!cacheConfig) { const container = this[core_1.INJECT_CONTAINER_KEY]; cacheConfig = await (0, cache_options_1.createCacheConfig)(cacheGroup, container, cacheInternalOptions); } if (!cacheConfig.passCondition(...args)) { return method.apply(this, args); } const extractedArgs = cacheConfig.extractArgs(...args); // if args is undefined so no cache if (extractedArgs === undefined) { return method.apply(this, args); } const cacheKey = cacheInternalOptions.keyGenerator(...cacheConfig.extractArgs(...args)); // cacheKey is undefined so we skip cache /* istanbul ignore next */ if (cacheKey === undefined) { return method.apply(this, args); } const result = await method.apply(this, args); if (!cacheConfig.veto(args, result)) { for (const cache of cacheConfig.caches) { // eslint-disable-next-line no-await-in-loop await cache.put(cacheKey, result); } } return result; }; });