Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NestJS Is a good aproach using DTO classes in request object?

I’m learning NestJS and now I’m working in a simple authentication application, at this point I configured global pipes to validations and I’m using dto classes for example to validate @Body() fields. I don’t know if I can use DTO to validate @Request fields sent from login endpoint.

import { Controller, Post, Request, UseGuards } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthGuard } from '@nestjs/passport';

    @Controller()
    export class AuthController {
      constructor(private authService: AuthService) {}
    
      @UseGuards(AuthGuard('local'))
      @Post('auth/login')
      async login(@Request() req: reqDto /* I would like to use DTO for validations*/) {
        return this.authService.login(req.user);
      }
    }

PS: I’m using DTO to validate SingUp body In UserController.

@Post('/signup')
  createUser(@Body() createUserDto: CreateUserDto) {
    return this.userService.createUser(createUserDto);
  }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

@Request() and @Headers() are two decorators that skip validation via pipes. You can make a custom request decorator that does get called via pipes, but annotating the request object would be a lot of work. What would be better is to create a decorator that gets just the data you need off the request, and then make a DTO for that object and validate that as necessary

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading