MCPcopy
hub / github.com/nestjs/nest / ContextIdFactory

Class ContextIdFactory

packages/core/helpers/context-id-factory.ts:43–100  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

41}
42
43export class ContextIdFactory {
44 private static strategy?: ContextIdStrategy;
45
46 /**
47 * Generates a context identifier based on the request object.
48 */
49 public static create(): ContextId {
50 return createContextId();
51 }
52
53 /**
54 * Generates a random identifier to track asynchronous execution context.
55 * @param request request object
56 */
57 public static getByRequest<T extends Record<any, any> = any>(
58 request: T,
59 propsToInspect: string[] = ['raw'],
60 ): ContextId {
61 if (!request) {
62 return ContextIdFactory.create();
63 }
64 if (request[REQUEST_CONTEXT_ID as any]) {
65 return request[REQUEST_CONTEXT_ID as any];
66 }
67 for (const key of propsToInspect) {
68 if (request[key]?.[REQUEST_CONTEXT_ID]) {
69 return request[key][REQUEST_CONTEXT_ID];
70 }
71 }
72 if (!this.strategy) {
73 return ContextIdFactory.create();
74 }
75 const contextId = createContextId();
76 const resolverObjectOrFunction = this.strategy.attach(contextId, request);
77 if (this.isContextIdResolverWithPayload(resolverObjectOrFunction!)) {
78 contextId.getParent = resolverObjectOrFunction.resolve;
79 contextId.payload = resolverObjectOrFunction.payload;
80 } else {
81 contextId.getParent = resolverObjectOrFunction;
82 }
83 return contextId;
84 }
85
86 /**
87 * Registers a custom context id strategy that lets you attach
88 * a parent context id to the existing context id object.
89 * @param strategy strategy instance
90 */
91 public static apply(strategy: ContextIdStrategy) {
92 this.strategy = strategy;
93 }
94
95 private static isContextIdResolverWithPayload(
96 resolverOrResolverFn: ContextIdResolver | ContextIdResolverFn,
97 ): resolverOrResolverFn is ContextIdResolver {
98 return isObject(resolverOrResolverFn);
99 }
100}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected