UNPKG

2.68 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.ContextIdFactory = exports.createContextId = void 0;
4const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
5const request_constants_1 = require("../router/request/request-constants");
6function createContextId() {
7 /**
8 * We are generating random identifier to track asynchronous
9 * execution context. An identifier does not have to be neither unique
10 * nor unpredictable because WeakMap uses objects as keys (reference comparison).
11 * Thus, even though identifier number might be equal, WeakMap would properly
12 * associate asynchronous context with its internal map values using object reference.
13 * Object is automatically removed once request has been processed (closure).
14 */
15 return { id: Math.random() };
16}
17exports.createContextId = createContextId;
18class ContextIdFactory {
19 /**
20 * Generates a context identifier based on the request object.
21 */
22 static create() {
23 return createContextId();
24 }
25 /**
26 * Generates a random identifier to track asynchronous execution context.
27 * @param request request object
28 */
29 static getByRequest(request, propsToInspect = ['raw']) {
30 if (!request) {
31 return ContextIdFactory.create();
32 }
33 if (request[request_constants_1.REQUEST_CONTEXT_ID]) {
34 return request[request_constants_1.REQUEST_CONTEXT_ID];
35 }
36 for (const key of propsToInspect) {
37 if (request[key]?.[request_constants_1.REQUEST_CONTEXT_ID]) {
38 return request[key][request_constants_1.REQUEST_CONTEXT_ID];
39 }
40 }
41 if (!this.strategy) {
42 return ContextIdFactory.create();
43 }
44 const contextId = createContextId();
45 const resolverObjectOrFunction = this.strategy.attach(contextId, request);
46 if (this.isContextIdResolverWithPayload(resolverObjectOrFunction)) {
47 contextId.getParent = resolverObjectOrFunction.resolve;
48 contextId.payload = resolverObjectOrFunction.payload;
49 }
50 else {
51 contextId.getParent = resolverObjectOrFunction;
52 }
53 return contextId;
54 }
55 /**
56 * Registers a custom context id strategy that lets you attach
57 * a parent context id to the existing context id object.
58 * @param strategy strategy instance
59 */
60 static apply(strategy) {
61 this.strategy = strategy;
62 }
63 static isContextIdResolverWithPayload(resolverOrResolverFn) {
64 return (0, shared_utils_1.isObject)(resolverOrResolverFn);
65 }
66}
67exports.ContextIdFactory = ContextIdFactory;