@nest-boot/request-context 7.4.0 → 7.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,61 @@
1
1
  import { RequestContext } from "./request-context";
2
+ /**
3
+ * Helper type that extracts the argument types of a method.
4
+ * @internal
5
+ */
2
6
  type MethodArgs<T, M extends keyof T> = T[M] extends (...args: infer A) => any ? A : never;
7
+ /**
8
+ * Method decorator that wraps the method execution in a new request context.
9
+ *
10
+ * This is useful for creating request contexts for background jobs, event handlers,
11
+ * or any other code that runs outside of HTTP request handling.
12
+ *
13
+ * @typeParam T - The class type containing the method
14
+ * @typeParam P - The property key of the method
15
+ * @param fn - A function that creates the RequestContext, receiving the class instance and method arguments
16
+ * @returns A method decorator
17
+ *
18
+ * @example Basic usage with a job processor
19
+ * ```typescript
20
+ * import { CreateRequestContext, RequestContext } from '@nest-boot/request-context';
21
+ *
22
+ * class JobProcessor {
23
+ * @CreateRequestContext((instance, jobData) =>
24
+ * new RequestContext({ type: 'job', id: jobData.id })
25
+ * )
26
+ * async processJob(jobData: { id: string; payload: any }) {
27
+ * // This code runs within a request context
28
+ * console.log(`Processing job ${RequestContext.id}`);
29
+ * // ...
30
+ * }
31
+ * }
32
+ * ```
33
+ *
34
+ * @example With service injection
35
+ * ```typescript
36
+ * import { Injectable } from '@nestjs/common';
37
+ * import { CreateRequestContext, RequestContext } from '@nest-boot/request-context';
38
+ *
39
+ * @Injectable()
40
+ * class EventHandler {
41
+ * @CreateRequestContext((instance, event) =>
42
+ * new RequestContext({
43
+ * type: 'event',
44
+ * id: event.correlationId,
45
+ * })
46
+ * )
47
+ * async handleEvent(event: { correlationId: string; data: any }) {
48
+ * // Access context within the handler
49
+ * RequestContext.set('eventType', event.data.type);
50
+ * await this.processEvent(event);
51
+ * }
52
+ *
53
+ * private async processEvent(event: any) {
54
+ * // Context is still available here
55
+ * const eventType = RequestContext.get('eventType');
56
+ * }
57
+ * }
58
+ * ```
59
+ */
3
60
  export declare function CreateRequestContext<T extends object, P extends keyof T>(fn: (instance: T, ...args: MethodArgs<T, P>) => RequestContext): (_target: T, _propertyKey: P, descriptor: PropertyDescriptor) => PropertyDescriptor;
4
61
  export {};
@@ -2,6 +2,59 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CreateRequestContext = CreateRequestContext;
4
4
  const request_context_1 = require("./request-context");
5
+ /**
6
+ * Method decorator that wraps the method execution in a new request context.
7
+ *
8
+ * This is useful for creating request contexts for background jobs, event handlers,
9
+ * or any other code that runs outside of HTTP request handling.
10
+ *
11
+ * @typeParam T - The class type containing the method
12
+ * @typeParam P - The property key of the method
13
+ * @param fn - A function that creates the RequestContext, receiving the class instance and method arguments
14
+ * @returns A method decorator
15
+ *
16
+ * @example Basic usage with a job processor
17
+ * ```typescript
18
+ * import { CreateRequestContext, RequestContext } from '@nest-boot/request-context';
19
+ *
20
+ * class JobProcessor {
21
+ * @CreateRequestContext((instance, jobData) =>
22
+ * new RequestContext({ type: 'job', id: jobData.id })
23
+ * )
24
+ * async processJob(jobData: { id: string; payload: any }) {
25
+ * // This code runs within a request context
26
+ * console.log(`Processing job ${RequestContext.id}`);
27
+ * // ...
28
+ * }
29
+ * }
30
+ * ```
31
+ *
32
+ * @example With service injection
33
+ * ```typescript
34
+ * import { Injectable } from '@nestjs/common';
35
+ * import { CreateRequestContext, RequestContext } from '@nest-boot/request-context';
36
+ *
37
+ * @Injectable()
38
+ * class EventHandler {
39
+ * @CreateRequestContext((instance, event) =>
40
+ * new RequestContext({
41
+ * type: 'event',
42
+ * id: event.correlationId,
43
+ * })
44
+ * )
45
+ * async handleEvent(event: { correlationId: string; data: any }) {
46
+ * // Access context within the handler
47
+ * RequestContext.set('eventType', event.data.type);
48
+ * await this.processEvent(event);
49
+ * }
50
+ *
51
+ * private async processEvent(event: any) {
52
+ * // Context is still available here
53
+ * const eventType = RequestContext.get('eventType');
54
+ * }
55
+ * }
56
+ * ```
57
+ */
5
58
  function CreateRequestContext(fn) {
6
59
  return (_target, _propertyKey, descriptor) => {
7
60
  if (descriptor.value) {
@@ -1 +1 @@
1
- {"version":3,"file":"create-request-context.decorator.js","sourceRoot":"","sources":["../src/create-request-context.decorator.ts"],"names":[],"mappings":";;AAMA,oDAeC;AArBD,uDAAmD;AAMnD,SAAgB,oBAAoB,CAClC,EAA8D;IAE9D,OAAO,CAAC,OAAU,EAAE,YAAe,EAAE,UAA8B,EAAE,EAAE;QACrE,IAAI,UAAU,CAAC,KAAK,EAAE,CAAC;YACrB,MAAM,QAAQ,GAAG,UAAU,CAAC,KAAK,CAAC;YAElC,UAAU,CAAC,KAAK,GAAG,UAAmB,GAAG,IAAsB;gBAC7D,MAAM,GAAG,GAAG,EAAE,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,CAAC;gBAC9B,OAAO,gCAAc,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;YACnE,CAAC,CAAC;QACJ,CAAC;QAED,OAAO,UAAU,CAAC;IACpB,CAAC,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"create-request-context.decorator.js","sourceRoot":"","sources":["../src/create-request-context.decorator.ts"],"names":[],"mappings":";;AA+DA,oDAeC;AA9ED,uDAAmD;AAUnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AACH,SAAgB,oBAAoB,CAClC,EAA8D;IAE9D,OAAO,CAAC,OAAU,EAAE,YAAe,EAAE,UAA8B,EAAE,EAAE;QACrE,IAAI,UAAU,CAAC,KAAK,EAAE,CAAC;YACrB,MAAM,QAAQ,GAAG,UAAU,CAAC,KAAK,CAAC;YAElC,UAAU,CAAC,KAAK,GAAG,UAAmB,GAAG,IAAsB;gBAC7D,MAAM,GAAG,GAAG,EAAE,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,CAAC;gBAC9B,OAAO,gCAAc,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;YACnE,CAAC,CAAC;QACJ,CAAC;QAED,OAAO,UAAU,CAAC;IACpB,CAAC,CAAC;AACJ,CAAC"}
package/dist/repl.d.ts CHANGED
@@ -1,2 +1,44 @@
1
1
  import { DynamicModule, Type } from "@nestjs/common";
2
- export declare function repl(module: Type | DynamicModule): Promise<import("repl").REPLServer>;
2
+ import type { REPLServer } from "repl";
3
+ /**
4
+ * Starts a REPL (Read-Eval-Print Loop) session with request context support.
5
+ *
6
+ * This function creates a NestJS application context and starts an interactive
7
+ * REPL session where all commands run within a request context. This is useful
8
+ * for debugging and testing services that depend on request context.
9
+ *
10
+ * The REPL session:
11
+ * - Runs within a request context of type 'repl'
12
+ * - Has access to all NestJS providers
13
+ * - Maintains context across async operations
14
+ *
15
+ * @param module - The NestJS module (class or DynamicModule) to create the context from
16
+ * @returns A promise that resolves to the REPL server instance
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * // repl.ts
21
+ * import { repl } from '@nest-boot/request-context';
22
+ * import { AppModule } from './app.module';
23
+ *
24
+ * async function bootstrap() {
25
+ * await repl(AppModule);
26
+ * }
27
+ *
28
+ * bootstrap();
29
+ * ```
30
+ *
31
+ * @example Running the REPL
32
+ * ```bash
33
+ * npx ts-node -r tsconfig-paths/register repl.ts
34
+ * ```
35
+ *
36
+ * @example Using services in REPL
37
+ * ```typescript
38
+ * // In the REPL session:
39
+ * > const userService = get(UserService)
40
+ * > await userService.findAll()
41
+ * > RequestContext.id // Access current context ID
42
+ * ```
43
+ */
44
+ export declare function repl(module: Type | DynamicModule): Promise<REPLServer>;
package/dist/repl.js CHANGED
@@ -45,6 +45,47 @@ const repl_native_commands_1 = require("@nestjs/core/repl/repl-native-commands")
45
45
  const async_hooks_1 = require("async_hooks");
46
46
  const stream_1 = require("stream");
47
47
  const request_context_1 = require("./request-context");
48
+ /**
49
+ * Starts a REPL (Read-Eval-Print Loop) session with request context support.
50
+ *
51
+ * This function creates a NestJS application context and starts an interactive
52
+ * REPL session where all commands run within a request context. This is useful
53
+ * for debugging and testing services that depend on request context.
54
+ *
55
+ * The REPL session:
56
+ * - Runs within a request context of type 'repl'
57
+ * - Has access to all NestJS providers
58
+ * - Maintains context across async operations
59
+ *
60
+ * @param module - The NestJS module (class or DynamicModule) to create the context from
61
+ * @returns A promise that resolves to the REPL server instance
62
+ *
63
+ * @example
64
+ * ```typescript
65
+ * // repl.ts
66
+ * import { repl } from '@nest-boot/request-context';
67
+ * import { AppModule } from './app.module';
68
+ *
69
+ * async function bootstrap() {
70
+ * await repl(AppModule);
71
+ * }
72
+ *
73
+ * bootstrap();
74
+ * ```
75
+ *
76
+ * @example Running the REPL
77
+ * ```bash
78
+ * npx ts-node -r tsconfig-paths/register repl.ts
79
+ * ```
80
+ *
81
+ * @example Using services in REPL
82
+ * ```typescript
83
+ * // In the REPL session:
84
+ * > const userService = get(UserService)
85
+ * > await userService.findAll()
86
+ * > RequestContext.id // Access current context ID
87
+ * ```
88
+ */
48
89
  async function repl(module) {
49
90
  const app = await core_1.NestFactory.createApplicationContext(module, {
50
91
  abortOnError: false,
package/dist/repl.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"repl.js","sourceRoot":"","sources":["../src/repl.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,oBA+CC;AA5DD,2CAA6D;AAC7D,0EAA2D;AAC3D,uCAA2C;AAC3C,mFAAyE;AACzE,2DAAuE;AACvE,iEAA6D;AAC7D,+DAA2D;AAC3D,iFAAqF;AACrF,6CAA4C;AAC5C,mCAAmC;AAEnC,uDAAmD;AAE5C,KAAK,UAAU,IAAI,CAAC,MAA4B;IACrD,MAAM,GAAG,GAAG,MAAM,kBAAW,CAAC,wBAAwB,CAAC,MAAM,EAAE;QAC7D,YAAY,EAAE,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,CAAC;gBACZ,SAAS,CAAC,KAAK,EAAE,QAAQ,EAAE,QAAQ;oBACjC,aAAa,CAAC,eAAe,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;gBAC7D,CAAC;aACF,CAAC,CACH,EACD;gBACE,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ;oBACxB,IAAI,IAAI,IAAI,MAAM,EAAE,CAAC;wBACnB,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;oBAC7C,CAAC;yBAAM,IAAI,IAAI,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;wBACjC,OAAO,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;oBACpD,CAAC;gBACH,CAAC;aACF,CACF;YACD,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,MAAM,EAAE,qBAAG,CAAC,KAAK,CAAC,IAAI,CAAC;YACvB,eAAe,EAAE,IAAI;SACtB,CAAC,CAAC;QAEH,IAAA,sCAAc,EAAC,UAAU,CAAC,OAAO,EAAE,WAAW,CAAC,WAAW,CAAC,CAAC;QAE5D,IAAA,kDAA2B,EAAC,UAAU,CAAC,CAAC;QAExC,OAAO,UAAU,CAAC;IACpB,CAAC,CACF,CAAC;AACJ,CAAC"}
@@ -1,2 +1,24 @@
1
+ /**
2
+ * Token for storing the HTTP request object in the request context.
3
+ *
4
+ * @example
5
+ * ```typescript
6
+ * import { REQUEST } from '@nest-boot/request-context';
7
+ * import { Request } from 'express';
8
+ *
9
+ * const req = RequestContext.get<Request>(REQUEST);
10
+ * ```
11
+ */
1
12
  export declare const REQUEST = "REQUEST";
13
+ /**
14
+ * Token for storing the HTTP response object in the request context.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { RESPONSE } from '@nest-boot/request-context';
19
+ * import { Response } from 'express';
20
+ *
21
+ * const res = RequestContext.get<Response>(RESPONSE);
22
+ * ```
23
+ */
2
24
  export declare const RESPONSE = "RESPONSE";
@@ -1,6 +1,28 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RESPONSE = exports.REQUEST = void 0;
4
+ /**
5
+ * Token for storing the HTTP request object in the request context.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { REQUEST } from '@nest-boot/request-context';
10
+ * import { Request } from 'express';
11
+ *
12
+ * const req = RequestContext.get<Request>(REQUEST);
13
+ * ```
14
+ */
4
15
  exports.REQUEST = "REQUEST";
16
+ /**
17
+ * Token for storing the HTTP response object in the request context.
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * import { RESPONSE } from '@nest-boot/request-context';
22
+ * import { Response } from 'express';
23
+ *
24
+ * const res = RequestContext.get<Response>(RESPONSE);
25
+ * ```
26
+ */
5
27
  exports.RESPONSE = "RESPONSE";
6
28
  //# sourceMappingURL=request-context.constants.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"request-context.constants.js","sourceRoot":"","sources":["../src/request-context.constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,OAAO,GAAG,SAAS,CAAC;AACpB,QAAA,QAAQ,GAAG,UAAU,CAAC"}
1
+ {"version":3,"file":"request-context.constants.js","sourceRoot":"","sources":["../src/request-context.constants.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;GAUG;AACU,QAAA,OAAO,GAAG,SAAS,CAAC;AAEjC;;;;;;;;;;GAUG;AACU,QAAA,QAAQ,GAAG,UAAU,CAAC"}
@@ -1,33 +1,327 @@
1
1
  import { type Type } from "@nestjs/common";
2
+ /**
3
+ * Middleware function type for request context.
4
+ * Middlewares are executed in order when running a request context.
5
+ *
6
+ * @typeParam T - The return type of the middleware chain
7
+ * @param ctx - The current request context
8
+ * @param next - Function to call the next middleware in the chain
9
+ * @returns A promise resolving to the result of the middleware chain
10
+ */
2
11
  type RequestContextMiddleware = <T>(ctx: RequestContext, next: () => Promise<T>) => Promise<T>;
12
+ /**
13
+ * Options for creating a new RequestContext instance.
14
+ */
3
15
  export interface RequestContextCreateOptions {
16
+ /**
17
+ * Unique identifier for the request context.
18
+ * If not provided, a random UUID will be generated.
19
+ */
4
20
  id?: string;
21
+ /**
22
+ * The type of context (e.g., 'http', 'graphql', 'repl', 'job').
23
+ */
5
24
  type: string;
25
+ /**
26
+ * Parent context for creating nested/child contexts.
27
+ * Child contexts can access values from parent contexts.
28
+ */
6
29
  parent?: RequestContext;
7
30
  }
31
+ /**
32
+ * RequestContext provides a way to store and access request-scoped data
33
+ * throughout the lifecycle of a request using AsyncLocalStorage.
34
+ *
35
+ * This is useful for storing data like the current user, request ID,
36
+ * database transactions, and other request-specific information that
37
+ * needs to be accessed across different parts of the application.
38
+ *
39
+ * @example Basic usage
40
+ * ```typescript
41
+ * import { RequestContext } from '@nest-boot/request-context';
42
+ *
43
+ * // Get the current request ID
44
+ * const requestId = RequestContext.id;
45
+ *
46
+ * // Store a value in the context
47
+ * RequestContext.set('userId', 123);
48
+ *
49
+ * // Retrieve a value from the context
50
+ * const userId = RequestContext.get<number>('userId');
51
+ * ```
52
+ *
53
+ * @example Running code in a new context
54
+ * ```typescript
55
+ * await RequestContext.run(
56
+ * new RequestContext({ type: 'job' }),
57
+ * async (ctx) => {
58
+ * ctx.set('jobId', 'abc123');
59
+ * await processJob();
60
+ * }
61
+ * );
62
+ * ```
63
+ *
64
+ * @example Creating a child context
65
+ * ```typescript
66
+ * await RequestContext.child(async (childCtx) => {
67
+ * // Child context inherits values from parent
68
+ * // but can have its own values that don't affect parent
69
+ * childCtx.set('tempValue', 'only in child');
70
+ * });
71
+ * ```
72
+ */
8
73
  export declare class RequestContext {
74
+ /**
75
+ * Unique identifier for this request context.
76
+ * Automatically generated as a UUID if not provided.
77
+ */
9
78
  readonly id: string;
79
+ /**
80
+ * The type of this context (e.g., 'http', 'graphql', 'repl', 'job').
81
+ */
10
82
  readonly type: string;
83
+ /**
84
+ * Parent context, if this is a child context.
85
+ * Values not found in this context will be looked up in the parent.
86
+ */
11
87
  readonly parent?: RequestContext;
88
+ /** @internal */
12
89
  private readonly container;
90
+ /** @internal */
13
91
  private static readonly storage;
92
+ /** @internal */
14
93
  private static readonly middlewares;
94
+ /** @internal */
15
95
  private static readonly middlewareDependencies;
96
+ /** @internal */
16
97
  private static middlewaresStack;
98
+ /**
99
+ * Creates a new RequestContext instance.
100
+ *
101
+ * @param options - Configuration options for the context
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * const ctx = new RequestContext({
106
+ * id: 'custom-id',
107
+ * type: 'http',
108
+ * });
109
+ * ```
110
+ */
17
111
  constructor(options: RequestContextCreateOptions);
112
+ /**
113
+ * Gets a value from the context by its token.
114
+ * If not found in this context, looks up the parent context.
115
+ *
116
+ * @typeParam T - The expected type of the value
117
+ * @param token - The key to look up (string, symbol, function, or class)
118
+ * @returns The value if found, otherwise undefined
119
+ *
120
+ * @example
121
+ * ```typescript
122
+ * const ctx = RequestContext.current();
123
+ * const user = ctx.get<User>('currentUser');
124
+ * const service = ctx.get(MyService);
125
+ * ```
126
+ */
18
127
  get<T>(token: string | symbol | Function | Type<T>): T | undefined;
128
+ /**
129
+ * Sets a value in the context.
130
+ *
131
+ * @typeParam T - The type of the value
132
+ * @param typeOrToken - The key to store the value under
133
+ * @param value - The value to store
134
+ *
135
+ * @example
136
+ * ```typescript
137
+ * const ctx = RequestContext.current();
138
+ * ctx.set('userId', 123);
139
+ * ctx.set(UserService, userServiceInstance);
140
+ * ```
141
+ */
19
142
  set<T>(typeOrToken: string | symbol | Type<T>, value: T): void;
143
+ /**
144
+ * Gets a value from the context, or sets it if not present.
145
+ *
146
+ * @typeParam T - The type of the value
147
+ * @param typeOrToken - The key to look up or store under
148
+ * @param value - The value to set if not already present
149
+ * @returns The existing value or the newly set value
150
+ *
151
+ * @example
152
+ * ```typescript
153
+ * const ctx = RequestContext.current();
154
+ * const cache = ctx.getOrSet('cache', new Map());
155
+ * ```
156
+ */
20
157
  getOrSet<T>(typeOrToken: string | symbol | Type<T>, value: T): T;
158
+ /**
159
+ * Gets a value from the current context by its key.
160
+ * Static method that accesses the current context automatically.
161
+ *
162
+ * @typeParam T - The expected type of the value
163
+ * @param key - The key to look up
164
+ * @returns The value if found, otherwise undefined
165
+ * @throws Error if no request context is active
166
+ *
167
+ * @example
168
+ * ```typescript
169
+ * const userId = RequestContext.get<number>('userId');
170
+ * ```
171
+ */
21
172
  static get<T>(key: string | symbol | Function | Type<T>): T | undefined;
173
+ /**
174
+ * Sets a value in the current context.
175
+ * Static method that accesses the current context automatically.
176
+ *
177
+ * @typeParam T - The type of the value
178
+ * @param key - The key to store the value under
179
+ * @param value - The value to store
180
+ * @throws Error if no request context is active
181
+ *
182
+ * @example
183
+ * ```typescript
184
+ * RequestContext.set('userId', 123);
185
+ * ```
186
+ */
22
187
  static set<T>(key: string | symbol | Type<T>, value: T): void;
188
+ /**
189
+ * Gets a value from the current context, or sets it if not present.
190
+ * Static method that accesses the current context automatically.
191
+ *
192
+ * @typeParam T - The type of the value
193
+ * @param key - The key to look up or store under
194
+ * @param value - The value to set if not already present
195
+ * @returns The existing value or the newly set value
196
+ * @throws Error if no request context is active
197
+ *
198
+ * @example
199
+ * ```typescript
200
+ * const cache = RequestContext.getOrSet('cache', new Map());
201
+ * ```
202
+ */
23
203
  static getOrSet<T>(key: string | symbol | Type<T>, value: T): T;
204
+ /**
205
+ * Gets the ID of the current request context.
206
+ *
207
+ * @returns The unique identifier of the current context
208
+ * @throws Error if no request context is active
209
+ *
210
+ * @example
211
+ * ```typescript
212
+ * console.log(`Processing request ${RequestContext.id}`);
213
+ * ```
214
+ */
24
215
  static get id(): string;
216
+ /**
217
+ * Gets the current request context.
218
+ *
219
+ * @returns The current RequestContext instance
220
+ * @throws Error if no request context is active
221
+ *
222
+ * @example
223
+ * ```typescript
224
+ * const ctx = RequestContext.current();
225
+ * console.log(ctx.type); // 'http'
226
+ * ```
227
+ */
25
228
  static current(): RequestContext;
229
+ /**
230
+ * Checks if a request context is currently active.
231
+ *
232
+ * @returns true if a context is active, false otherwise
233
+ *
234
+ * @example
235
+ * ```typescript
236
+ * if (RequestContext.isActive()) {
237
+ * const userId = RequestContext.get('userId');
238
+ * }
239
+ * ```
240
+ */
26
241
  static isActive(): boolean;
242
+ /**
243
+ * Runs a callback within a request context.
244
+ * All registered middlewares are executed before the callback.
245
+ *
246
+ * @typeParam T - The return type of the callback
247
+ * @param ctx - The request context to run within
248
+ * @param callback - The function to execute within the context
249
+ * @returns A promise resolving to the callback's return value
250
+ *
251
+ * @example
252
+ * ```typescript
253
+ * const result = await RequestContext.run(
254
+ * new RequestContext({ type: 'job' }),
255
+ * async (ctx) => {
256
+ * ctx.set('jobId', 'abc123');
257
+ * return await processJob();
258
+ * }
259
+ * );
260
+ * ```
261
+ */
27
262
  static run<T>(ctx: RequestContext, callback: (ctx: RequestContext) => T | Promise<T>): Promise<T>;
263
+ /**
264
+ * Creates and runs a child context that inherits from the current context.
265
+ * Child contexts can read values from parent contexts but modifications
266
+ * are isolated to the child.
267
+ *
268
+ * @typeParam T - The return type of the callback
269
+ * @param callback - The function to execute within the child context
270
+ * @returns A promise resolving to the callback's return value
271
+ * @throws Error if no request context is active
272
+ *
273
+ * @example
274
+ * ```typescript
275
+ * // In parent context
276
+ * RequestContext.set('userId', 123);
277
+ *
278
+ * await RequestContext.child(async (childCtx) => {
279
+ * // Can read parent values
280
+ * const userId = childCtx.get('userId'); // 123
281
+ *
282
+ * // Child-only values don't affect parent
283
+ * childCtx.set('tempData', 'child only');
284
+ * });
285
+ *
286
+ * // Parent context unchanged
287
+ * RequestContext.get('tempData'); // undefined
288
+ * ```
289
+ */
28
290
  static child<T>(callback: (ctx: RequestContext) => T | Promise<T>): Promise<T>;
291
+ /**
292
+ * Registers a middleware to be executed when running a request context.
293
+ * Middlewares are executed in dependency order.
294
+ *
295
+ * @param name - Unique name for the middleware
296
+ * @param middleware - The middleware function to register
297
+ * @param dependencies - Names of middlewares that must run before this one
298
+ *
299
+ * @example
300
+ * ```typescript
301
+ * RequestContext.registerMiddleware(
302
+ * 'auth',
303
+ * async (ctx, next) => {
304
+ * ctx.set('user', await loadUser());
305
+ * return next();
306
+ * }
307
+ * );
308
+ *
309
+ * // Middleware with dependencies
310
+ * RequestContext.registerMiddleware(
311
+ * 'permissions',
312
+ * async (ctx, next) => {
313
+ * const user = ctx.get('user');
314
+ * ctx.set('permissions', await loadPermissions(user));
315
+ * return next();
316
+ * },
317
+ * ['auth'] // Runs after 'auth' middleware
318
+ * );
319
+ * ```
320
+ */
29
321
  static registerMiddleware(name: string, middleware: RequestContextMiddleware, dependencies?: string[]): void;
322
+ /** @internal */
30
323
  private static resolveDependencies;
324
+ /** @internal */
31
325
  private static generateMiddlewaresStack;
32
326
  }
33
327
  export {};
@@ -1,5 +1,35 @@
1
1
  import { type CallHandler, type ExecutionContext, type NestInterceptor } from "@nestjs/common";
2
2
  import { Observable } from "rxjs";
3
+ /**
4
+ * NestJS interceptor that creates request context for HTTP and GraphQL requests.
5
+ *
6
+ * This interceptor serves as a fallback for cases where the middleware doesn't
7
+ * run (e.g., GraphQL resolvers). It:
8
+ * - Creates a new RequestContext if one doesn't already exist
9
+ * - Uses the `x-request-id` header as the context ID if provided
10
+ * - Supports both HTTP and GraphQL execution contexts
11
+ *
12
+ * The interceptor is automatically registered by RequestContextModule.
13
+ *
14
+ * @example
15
+ * The interceptor is typically used automatically, but can be applied manually:
16
+ * ```typescript
17
+ * import { Controller, UseInterceptors } from '@nestjs/common';
18
+ * import { RequestContextInterceptor } from '@nest-boot/request-context';
19
+ *
20
+ * @Controller()
21
+ * @UseInterceptors(RequestContextInterceptor)
22
+ * export class MyController {}
23
+ * ```
24
+ */
3
25
  export declare class RequestContextInterceptor implements NestInterceptor {
26
+ /**
27
+ * Intercepts the request and wraps execution in a request context.
28
+ *
29
+ * @typeParam T - The type of the response
30
+ * @param executionContext - The NestJS execution context
31
+ * @param next - The call handler for the next interceptor or handler
32
+ * @returns An observable of the response
33
+ */
4
34
  intercept<T>(executionContext: ExecutionContext, next: CallHandler<T>): Observable<T>;
5
35
  }