UNPKG

nestjs-cls

Version:

A continuation-local storage module compatible with NestJS's dependency injection.

49 lines (48 loc) 2.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UseCls = UseCls; require("reflect-metadata"); const copy_method_metadata_1 = require("../../utils/copy-method-metadata"); const cls_service_manager_1 = require("../cls-service-manager"); const cls_constants_1 = require("../cls.constants"); const cls_options_1 = require("../cls.options"); const cls_plugin_hooks_host_1 = require("../plugin/cls-plugin-hooks-host"); function UseCls(maybeOptions) { return (target, propertyKey, descriptor) => { const options = { ...new cls_options_1.ClsDecoratorOptions(), ...maybeOptions }; const cls = cls_service_manager_1.ClsServiceManager.getClsService(); const original = descriptor.value; if (typeof original !== 'function') { throw new Error(`The @UseCls decorator can be only used on functions, but ${propertyKey.toString()} is not a function.`); } descriptor.value = new Proxy(original, { apply: function (_, outerThis, args) { const pluginHooks = cls_plugin_hooks_host_1.ClsPluginsHooksHost.getInstance(); return cls.run(options.runOptions ?? {}, async () => { const pluginCtx = { kind: 'decorator', args, }; if (options.initializePlugins) { await pluginHooks.beforeSetup(pluginCtx); } if (options.generateId) { const id = await options.idGenerator?.apply(outerThis, args); cls.set(cls_constants_1.CLS_ID, id); } if (options.setup) { await options.setup.apply(outerThis, [cls, ...args]); } if (options.initializePlugins) { await pluginHooks.afterSetup(pluginCtx); } if (options.resolveProxyProviders) { await cls.proxy.resolve(); } return original.apply(outerThis, args); }); }, }); (0, copy_method_metadata_1.copyMethodMetadata)(original, descriptor.value); }; }