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

Time:10-03

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);
  }

CodePudding user response:

@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

  • Related