UNPKG

@gabliam/cache

Version:
57 lines (56 loc) 2.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Cacheable = void 0; /* eslint-disable @typescript-eslint/no-redeclare */ const core_1 = require("@gabliam/core"); const constant_1 = require("../constant"); const cache_options_1 = require("./cache-options"); exports.Cacheable = (0, core_1.makePropDecorator)('Cacheable', (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); } let result = constant_1.NO_RESULT; for (const cache of cacheConfig.caches) { // eslint-disable-next-line no-await-in-loop const val = await cache.get(cacheKey); if (val !== undefined && val !== constant_1.NO_RESULT) { result = val; break; } } if (result === constant_1.NO_RESULT) { 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.putIfAbsent(cacheKey, result); } } return result; }; });