【问题标题】:How can I use validation groups for DTOs in a NestJS controller?如何在 NestJS 控制器中为 DTO 使用验证组?
【发布时间】:2022-02-09 20:40:26
【问题描述】:

我想在我的 DTO 中使用验证组并在我的控制器中使用它们。有谁知道如何使用/将验证组传递给控制器​​或让request.user 自动将其传递给控制器​​?

create-user.dto.ts

export class CreateUserDto {
  @IsNotEmpty({
    groups: ["admin"],
  })
  role: string;

  @IsNotEmpty()
  @IsEmail()
  email: string;

  @IsNotEmpty()
  password: string;
}

users.controller.ts

@Controller('users')
@UseGuards(JwtAuthGuard)
@UseInterceptors(ClassSerializerInterceptor)
export class UsersController {
  constructor(
    private readonly usersService: UsersService,
  ) {}

  @Post()
  async create(@Body() createUserDto: CreateUserDto): Promise<User> {
    const result = await this.usersService.create(createUserDto);
    return result;
  }
}

【问题讨论】:

    标签: typescript nestjs dto class-validator class-transformer


    【解决方案1】:

    @IsNotEmpty@IsEmail 装饰器来自 class-validator 库,因此您应该使用 ValidationPipe

    关于验证的 Nest JS 文档:https://docs.nestjs.com/techniques/validation

    更新了 users.controller.ts

    @Controller('users')
    @UseGuards(JwtAuthGuard)
    export class UsersController {
      constructor(
        private readonly usersService: UsersService,
      ) {}
    
      @Post()
      @UsePipes(new ValidationPipe({ groups: ["admin"] }))
      async create(@Body() createUserDto: CreateUserDto): Promise<User> {
        const result = await this.usersService.create(createUserDto);
        return result;
      }
    }
    

    【讨论】:

    • 我实际上在全局上有验证管道,问题是如果我对组进行硬编码,添加上面提到的管道可以工作,但我想根据请求用户的组进行验证。跨度>
    猜你喜欢
    • 2021-08-10
    • 2021-12-14
    • 2020-01-07
    • 2020-09-30
    • 2013-10-06
    • 2022-09-23
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多