• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

313
Vistas
Nestjs What is the right order for @Body(), @Params(), @Req(), @Res()

I want to access the res object to send httpOnly cookies and need to validate body with DTO. but every time i try to do it something go wrong what is the right order for these params?

almost 3 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

There is no strict order that needs to be followed. Each controller method may use decorators for retrieving different things (see controller docs: https://docs.nestjs.com/controllers)

Example

Let's imagine you are building an endpoint for handling some kind of search using a POST request and a payload. Nest returns some results and sets cookies with the latest performed search timestamp.

That sounds like your requirements, right?

Add cookie parser to nest application

Make sure you followed cookies documentation and installed all dependencies together and configured cookie parser middleware: https://docs.nestjs.com/techniques/cookies

Search payload data transfer object (DTO)

import { IsInt, IsNotEmpty } from 'class-validator';

export class SearchBodyDto {
  @IsNotEmpty()
  searchPhrase: string;

  @IsInt()
  page = 1;
}

Controller method

import { Request, Response } from 'express';
import { Body, Controller, Post, Req, Res } from '@nestjs/common';

@Controller()
export class AppController {
  @Post('/search')
  async search(
    @Body() body: SearchBodyDto,
    @Req() req: Request,
    // passthrough:true here leaves response handling to framework.
    // Otherwise you would need to send response manually, like: `res.json({data})`
    @Res({ passthrough: true }) res: Response,
  ) {
    const currentTimestamp = new Date().toISOString();
    // Save to cookies current timestamp of search.
    res.cookie('lastSearch', currentTimestamp, { httpOnly: true });
    return {
      // Return last search timestamp and fallback to current timestamp.
      lastSearch: req.cookies.lastSearch ?? currentTimestamp,
      // Validated search phrase from DTO.
      searchPhrase: body.searchPhrase,
      // Page by default 1.
      page: body.page,
      // Some example search results.
      searchResults: ['water', 'wind', 'earth'],
    };
  }
}

Result

Now when you do a request to the endpoint, you will see the latest search time in a response: postman example, and also that value will be set to 'lastSearch' cookie.

The payload still will be validated using decorators on DTO.

almost 3 years ago · Juan Pablo Isaza Denunciar

0

There are no order.

Also, they are parameter decorator factories, not parameters.

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda