Zum Inhalt springen

Parameter decorators in NestJS

@ Body() and @ Param() are just two of the most commonly used parameter decorators in NestJS. NestJS provides a rich set of decorators to extract data from various parts of an incoming HTTP request.

Query()

Example: GET /tasks?status=OPEN&limit=10

@Get()
getTasks(@Query('status') status: string, @Query('limit') limit: string) {
  // status will be 'OPEN', limit will be '10'
}

@Get()
getTasks(@Query() query: { status?: string; limit?: string }) {
  // query will be { status: 'OPEN', limit: '10' }
}

Headers()

Example: Authorization: Bearer

@Get()
getUser(@Headers('Authorization') authHeader: string) {
  // authHeader will be 'Bearer <token>'
}

@Get()
getRequestHeaders(@Headers() headers: Record<string, string>) {
  // headers will be an object containing all request headers
}

Ip()

@Get()
getIp(@Ip() ip: string) {
  // ip will be the client's IP address
}

HostParam()

Example: If your route is @Controller({ host: ‚:account.example.com‘ })

@Get()
getAccountData(@HostParam('account') account: string) {
  // account will be the subdomain, e.g., 'mycompany'
}

@Session()

import { Controller, Get, Session } from '@nestjs/common';

@Controller('session-example')
export class SessionController {
  @Get()
  getSessionData(@Session() session: Record<string, any>) {
    // Access and modify session data
    session.views = (session.views || 0) + 1;
    console.log('Session views:', session.views);
    return `You have viewed this page ${session.views} times.`;
  }
}

@Req() and @Res() (or @Response()):

  • @Req(): Provides the raw request object.
  • @Res() / @Response(): Provides the raw response object. Note: Using these means you lose some of Nest’s standard response handling features (e.g., interceptors, automatic serialization) and must manually send the response (res.send(), res.json(), res.end()).
import { Controller, Get, Req, Res } from '@nestjs/common';
import { Request, Response } from 'express'; // Import types for Express (or Fastify types)

@Controller('raw')
export class RawController {
  @Get('express')
  getRawExpress(
    @Req() request: Request,
    @Res() response: Response, // If you use @Res(), you must manually send the response
  ) {
    console.log('Raw Request Path:', request.path);
    response.status(200).json({ message: 'Hello from raw Express response!' });
  }
}
}

Custom Decorator

src/common/decorators/user.decorator.ts

import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const CurrentUser = createParamDecorator(
  (data: string, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    // 'data' could be used to specify a property, e.g., @CurrentUser('id')
    return data ? request.user?.[data] : request.user;
  },
);

Use it in UsersController

import { Controller, Get } from '@nestjs/common';
import { CurrentUser } from '../common/decorators/user.decorator'; // Adjust path

interface UserPayload {
  id: string;
  email: string;
  // ... other user properties
}

@Controller('users')
export class UsersController {
  @Get('me')
  getProfile(@CurrentUser() user: UserPayload) {
    console.log('Authenticated user:', user);
    return user;
  }

  @Get('my-id')
  getMyId(@CurrentUser('id') userId: string) {
    console.log('Authenticated user ID:', userId);
    return userId;
  }
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert