@imqueue/rpc
Version:
RPC-like client-service implementation over messaging queue
74 lines • 3.21 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.cache = void 0;
/*!
* IMQ-RPC Decorators: cache
*
* Copyright (c) 2018, imqueue.com <support@imqueue.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
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