UNPKG

1.78 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.ContextIdFactory = exports.createContextId = void 0;
4const request_constants_1 = require("../router/request/request-constants");
5function createContextId() {
6 /**
7 * We are generating random identifier to track asynchronous
8 * execution context. An identifier does not have to be neither unique
9 * nor unpredictable because WeakMap uses objects as keys (reference comparison).
10 * Thus, even though identifier number might be equal, WeakMap would properly
11 * associate asynchronous context with its internal map values using object reference.
12 * Object is automatically removed once request has been processed (closure).
13 */
14 return { id: Math.random() };
15}
16exports.createContextId = createContextId;
17class ContextIdFactory {
18 /**
19 * Generates a context identifier based on the request object.
20 */
21 static create() {
22 return createContextId();
23 }
24 /**
25 * Generates a random identifier to track asynchronous execution context.
26 * @param request request object
27 */
28 static getByRequest(request, propsToInspect = ['raw']) {
29 var _a;
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 ((_a = request[key]) === null || _a === void 0 ? void 0 : _a[request_constants_1.REQUEST_CONTEXT_ID]) {
38 return request[key][request_constants_1.REQUEST_CONTEXT_ID];
39 }
40 }
41 return ContextIdFactory.create();
42 }
43}
44exports.ContextIdFactory = ContextIdFactory;