Kind: Function
Source: packages/common/decorators/http/create-route-param-metadata.decorator.ts
Part of: Common
Defines HTTP route param decorator
createParamDecorator creates custom parameter decorators for HTTP route handlers. It stores parameter metadata and invokes a factory callback at request time, allowing handlers to receive values derived from the request, response, or execution context.
Signature
tsfunction createParamDecorator(factory: CustomParamFactory<FactoryData, FactoryOutput>, enhancers: ParamDecoratorEnhancer[]): ( ...dataOrPipes: (Type<PipeTransform> | PipeTransform | FactoryData)[] ) => ParameterDecorator
Parameters
| Name | Type |
|---|---|
factory | CustomParamFactory<FactoryData, FactoryOutput> |
enhancers | ParamDecoratorEnhancer[] |
Returns: ( ...dataOrPipes: (Type<PipeTransform> | PipeTransform | FactoryData)[] ) => ParameterDecorator
Diagram
mermaidgraph LR A[HTTP Request] --> B[Route Handler] B --> C[Custom Parameter Decorator] C --> D[Factory Callback] D --> E[ExecutionContext] E --> F[Extracted Parameter Value] F --> G[Handler Method Argument]
Usage
tsimport { createParamDecorator, ExecutionContext } from '@nestjs/common';
export const CurrentUser = createParamDecorator(
(property: string | undefined, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
const user = request.user;
return property ? user?.[property] : user;
},
);
// Usage in a controller
@Get('profile')
getProfile(
@CurrentUser() user: User,
@CurrentUser('id') userId: string,
) {
return { user, userId };
}
AI Coding Instructions
- Use the factory callback to extract values from
ExecutionContext, typically throughctx.switchToHttp().getRequest(). - Treat the optional
dataargument as decorator configuration, such as a property name or lookup key. - Keep decorators focused on extracting request-scoped values; place business logic in guards, services, or controllers.
- Ensure extracted values handle missing request properties safely, especially for optional authentication data.
- Use the resulting decorator on controller method parameters and combine it with pipes when validation or transformation is needed.
Was this page helpful?