如何在控制器中覆盖全局ValidationPipe?

时间:2019-05-23 10:46:07

标签: typescript nestjs class-validator

我使用带有ValidationPipe选项的全局{ transform: true, whitelist: true }。但是,在特定的控制器请求中,我想使用类验证器的验证组技术来重用相同的类,但使用不同的验证。因此,有必要重写管道的选项以应用新选项。

这是在NestJS 6.2.4上。我尝试在@Query(new ValidationPipe({groups: ['res']}))应用新管道,但是全局管道仍然适用。我对@UsePipes()应用了相同的逻辑,但是再次应用了全局管道。

此外,我尝试将always: false属性与组一起应用,以避免始终验证该属性,但是由于这是默认行为,因此并没有太大帮助。

@IsNumberString({ groups: ['res'] })
resId: number;

1 个答案:

答案 0 :(得分:0)

In this case, what I would recommend is to add the ValidationPipe at the method level within your controller, instead of at the controller level.

Something like this:

@Controller('users')
export class UsersController {

    constructor(
        private readonly usersService: UsersService
    ) {
    }

    @Post()
    @UsePipes(new ValidationPipe({
        forbidUnknownValues: true,
        transform: true
    }))
    async create(@Body() createUserDtoReq: CreateUserRequestDto): Promise<UserResponseDto> {
        return await this.usersService.create(createUserDtoReq);
    }
}

Others might add other suggestions though.

相关问题