@imqueue/rpc
Version:
RPC-like client-service implementation over messaging queue
80 lines • 3.37 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.cache = void 0;
/*!
* IMQ-RPC Decorators: cache
*
* I'm Queue Software Project
* Copyright (C) 2025 imqueue.com <support@imqueue.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* If you want to use this code in a closed source (commercial) project, you can
* purchase a proprietary commercial license. Please contact us at
* <support@imqueue.com> to get commercial licensing options.
*/
const __1 = require("..");
// codebeat:disable[BLOCK_NESTING]
const cache = function (options) {
const cacheOptions = Object.assign(Object.assign({}, exports.cache.globalOptions), options);
let Adapter = cacheOptions.adapter || __1.RedisCache;
return function (target, methodName, descriptor) {
const original = descriptor.value;
descriptor.value = async function (...args) {
const context = this;
const className = this.constructor.name;
if (!context.cache) {
let cache = __1.IMQCache.get(Adapter);
// istanbul ignore next
if (cache && cache.ready) {
context.cache = cache;
}
else {
let opts = undefined;
if (context.imq && context.imq.writer) {
opts = { conn: context.imq.writer };
}
const logger = context.logger ||
(context.imq && context.imq.logger);
if (logger) {
opts = Object.assign(Object.assign({}, opts), { logger });
}
await __1.IMQCache.register(Adapter, opts).init();
context.cache = __1.IMQCache.get(Adapter);
}
}
try {
const key = (0, __1.signature)(className, methodName, args);
let result = await context.cache.get(key);
if (result === undefined) {
result = original.apply(this, args);
await context.cache.set(key, result, cacheOptions.ttl, !!cacheOptions.nx);
}
return result;
}
catch (err) {
// istanbul ignore next
(this.logger || context.cache.logger).warn('cache: Error fetching cached value for %s.%s(), args: %s!', className, methodName, JSON.stringify(args), err);
// istanbul ignore next
return original.apply(this, args);
}
};
};
};
exports.cache = cache;
// codebeat:enable[BLOCK_NESTING]
exports.cache.globalOptions = {
adapter: __1.RedisCache
};
//# sourceMappingURL=cache.js.map