Kind: Interface
Source: packages/core/helpers/context-id-factory.ts
Part of: Core
ContextIdResolver defines how Nest resolves a dependency-injection context ID for a given request or runtime payload. It pairs the original payload with a resolve function that selects the appropriate ContextId, enabling custom request-scoped and durable provider behavior.
Properties
| Property | Type |
|---|---|
payload | unknown |
resolve | ContextIdResolverFn |
Diagram
mermaidgraph LR A[Incoming Request / Payload] --> B[ContextIdStrategy.attach] B --> C[ContextIdResolver] C --> D[payload] C --> E[resolve HostComponentInfo] E --> F[ContextId] F --> G[Request-Scoped Provider Resolution]
Usage
tsimport {
ContextIdFactory,
ContextIdResolver,
ContextIdStrategy,
HostComponentInfo,
} from '@nestjs/core';
class CustomContextIdStrategy implements ContextIdStrategy {
attach(contextId: object, request: unknown): ContextIdResolver {
return {
payload: request,
resolve: (info: HostComponentInfo) => {
// Reuse the same context for durable dependency trees.
if (info.isTreeDurable) {
return contextId;
}
// Create an isolated context for non-durable providers.
return ContextIdFactory.create();
},
};
}
}
ContextIdFactory.apply(new CustomContextIdStrategy());
AI Coding Instructions
- Return both the original request or runtime value through
payloadand aresolvefunction for selecting context IDs. - Use
resolveto distinguish durable provider trees from providers that require isolated request contexts. - Ensure
resolvealways returns a validContextId, typically the suppliedcontextIdor one created withContextIdFactory.create(). - Register custom resolver behavior through a
ContextIdStrategyandContextIdFactory.apply(), rather than constructing resolvers in application code. - Avoid storing mutable request-specific state in shared resolver instances; use the
payloadfor per-request data.
Was this page helpful?