@gabliam/cache
Version:
cache plugin for gabliam
71 lines (70 loc) • 2.89 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheEvict = void 0;
/* eslint-disable @typescript-eslint/no-redeclare */
const core_1 = require("@gabliam/core");
const cache_options_1 = require("./cache-options");
function isCacheEvictOptions(obj) {
return (typeof obj === 'object' &&
Object.prototype.hasOwnProperty.call(obj, 'cacheNames'));
}
function extractCacheEvictInternalOptions(value) {
let allEntries = false;
let beforeInvocation = false;
if (isCacheEvictOptions(value)) {
({ allEntries = false, beforeInvocation = false } = value);
}
return Object.assign(Object.assign({}, (0, cache_options_1.extractCacheInternalOptions)(value)), { allEntries,
beforeInvocation });
}
async function evict(caches, cacheKey, allEntries) {
for (const cache of caches) {
if (allEntries) {
// eslint-disable-next-line no-await-in-loop
await cache.clear();
}
else {
// eslint-disable-next-line no-await-in-loop
await cache.evict(cacheKey);
}
}
}
exports.CacheEvict = (0, core_1.makePropDecorator)('CacheEvict', (value) => extractCacheEvictInternalOptions(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);
}
if (cacheInternalOptions.beforeInvocation) {
await evict(cacheConfig.caches, cacheKey, cacheInternalOptions.allEntries);
}
const result = await method.apply(this, args);
if (!cacheInternalOptions.beforeInvocation &&
!cacheConfig.veto(args, result)) {
await evict(cacheConfig.caches, cacheKey, cacheInternalOptions.allEntries);
}
return result;
};
});