我想在我的 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/