Skip to content

createParamDecorator

reference
1 min readUpdated

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

ts
function createParamDecorator(factory: CustomParamFactory<FactoryData, FactoryOutput>, enhancers: ParamDecoratorEnhancer[]): ( ...dataOrPipes: (Type<PipeTransform> | PipeTransform | FactoryData)[] ) => ParameterDecorator

Parameters

NameType
factoryCustomParamFactory<FactoryData, FactoryOutput>
enhancersParamDecoratorEnhancer[]

Returns: ( ...dataOrPipes: (Type<PipeTransform> | PipeTransform | FactoryData)[] ) => ParameterDecorator

Diagram

mermaid
graph 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

ts
import { 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 through ctx.switchToHttp().getRequest().
  • Treat the optional data argument 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?

Download as PDF
createParamDecorator — NestJS head-to-head