typescript - 如何在 NestJS Controller 中使用 DTO 的验证组?

标签 typescript nestjs dto class-validator class-transformer

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

创建用户.dto.ts

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

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

  @IsNotEmpty()
  password: string;
}

用户.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;
  }
}

最佳答案

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

关于typescript - 如何在 NestJS Controller 中使用 DTO 的验证组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71037977/

相关文章:

typescript 定义。全局变量和模块名称相同

typescript - 仅用于类型检查的引用 .ts 文件

postgresql - 应用程序容器未正确连接到部署中的 postgres 数据库

java - Hibernate 对象和 GWT-RPC

web-applications - 在没有 DTO 的情况下直接在 Web 层中操作 JPA 实体

typescript :如何从继承的静态属性返回子类类型?

javascript - 将枚举对象转换为数组在 javascript 中返回额外的对象

node.js - 如何确保至少一个字段不为空?(如果只有一个不为空就可以了)

javascript - 在 Nest.js 应用程序中使用 typeOrm 订购所需的集合

java - 具有不同字段数量的 html 表单的域传输对象