Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

388
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

There are no order.

Also, they are parameter decorator factories, not parameters.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda