Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

169
Views
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?

7 months ago · Juan Pablo Isaza
2 answers
Answer question

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.

7 months ago · Juan Pablo Isaza Report

0

There are no order.

Also, they are parameter decorator factories, not parameters.

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.