UNPKG

nestjs-cls

Version:

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

57 lines 2.37 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ContextClsStoreMap = void 0; /** * This static class can be used to save the CLS store in a WeakMap based on the ExecutionContext * or any object that is passed to the `setByRawContext` method. * * It is used internally by the `ClsMiddleware`, `ClsInterceptor` and `ClsGuard` to prevent * instantiating the context multiple times for the same request. * * It can also be used as an escape hatch to retrieve the CLS store based on the ExecutionContext * or the "raw context" when the ExecutionContext is not available. * * For HTTP, it is the Request (@Req) object * * For WS, it is the data object * * For RPC (microservices), it is the RpcContext (@Ctx) object * * For GraphQL, it is the GqlContext object */ class ContextClsStoreMap { constructor() { } static set(context, value) { const ctx = this.getContextByType(context); this.contextMap.set(ctx, value); } static get(context) { const ctx = this.getContextByType(context); return this.contextMap.get(ctx); } static setByRaw(ctx, value) { this.contextMap.set(ctx, value); } static getByRaw(ctx) { return this.contextMap.get(ctx); } static getContextByType(context) { switch (context.getType()) { case 'http': const request = context.switchToHttp().getRequest(); // Workaround for Fastify // When setting the request from ClsMiddleware, we only have access to the "raw" request // But when accessing it from other enhancers, we receive the "full" request. Therefore, // we have to reach into the "raw" property to be able to compare the identity of the request. return request.raw ?? request; case 'ws': return context.switchToWs(); case 'rpc': return context.switchToRpc().getContext(); case 'graphql': // As per the GqlExecutionContext, the context is the second argument return context.getArgByIndex(2); default: return {}; } } } exports.ContextClsStoreMap = ContextClsStoreMap; ContextClsStoreMap.contextMap = new WeakMap(); //# sourceMappingURL=context-cls-store-map.js.map