我试图弄清楚如何在API调用中正确地使用我的验证管道和类验证器。
我有一个DTO与类验证器装饰,这是行为如预期的。但是,我想利用“skipMissingProperties”来忽略对不存在的东西的验证(例如,屏幕截图中的“名称”)。
我的意图是能够拥有一个简单的DTO,它使用了许多装饰器,并且跳过了那些不存在的DTO的验证。
不幸的是,我对skipMissingProperties的使用似乎不正确,因为提供此选项仍然会引发DTO内部的验证错误。
如何将验证管道skipMissingProperties选项与类验证器装饰器一起使用?
使用下面的代码,如果我使用其他参数发出更新请求,但将“name”排除在主体之外,类验证器将从DTO级别抛出错误。
API控制器终结点:
@Put(':viewId')
public async updateView(
@Req() request: RequestExtended,
@Param('viewId') viewId: string,
@Body(new ValidationPipe({ skipMissingProperties: true })) updateView: UpdateViewDto)
: Promise<View> {
// Do some API stuff
}
UpdateViewDTO:
export class UpdateViewDto {
@IsString()
@MinLength(1, {
message: LanguageElements.VIEW_NAME_REQUIRED_ERROR_MSG,
})
@MaxLength(50, {
message: LanguageElements.VIEW_NAME_TOO_LONG_ERROR_MSG,
})
public readonly name?: string;
// Other properties
}
发布于 2019-12-13 19:31:56
在main.ts
中,可以将skipMissingProperties: true
直接添加到ValidationPipe中。
app.useGlobalPipes(
new ValidationPipe({
skipMissingProperties: true,
exceptionFactory: (errors: ValidationError[]) => {
return new BadRequestException(errors[0].constraints);
},
}),
);
https://stackoverflow.com/questions/51548984
复制相似问题