我试图使用类验证器来验证传入的数据.数据由对象数组组成.应验证每个对象.
我面临的问题是,当所有内容都正确输入时,我会不断出错.似乎父类正在使用其子类的属性进行判断,因此子类的每个属性都会抛出whitelistValidation
个错误.
这是正在生成的错误:
[
{
"target":{
"drainPoints":[
{
"drainPointType":"roundsurface",
"flowType":"normal",
"flowCoefficient":0.5,
"point":{
"x":0,
"y":0
}
}
]
},
"value":[
{
"drainPointType":"roundsurface",
"flowType":"normal",
"flowCoefficient":0.5,
"point":{
"x":0,
"y":0
}
}
],
"property":"drainPoints",
"children":[
{
"target":[
{
"drainPointType":"roundsurface",
"flowType":"normal",
"flowCoefficient":0.5,
"point":{
"x":0,
"y":0
}
}
],
"value":{
"drainPointType":"roundsurface",
"flowType":"normal",
"flowCoefficient":0.5,
"point":{
"x":0,
"y":0
}
},
"property":"0",
"children":[
{
"target":{
"drainPointType":"roundsurface",
"flowType":"normal",
"flowCoefficient":0.5,
"point":{
"x":0,
"y":0
}
},
"value":"roundsurface",
"property":"drainPointType",
"constraints":{
"whitelistValidation":"property drainPointType should not exist"
}
},
{
"target":{
"drainPointType":"roundsurface",
"flowType":"normal",
"flowCoefficient":0.5,
"point":{
"x":0,
"y":0
}
},
"value":"normal",
"property":"flowType",
"constraints":{
"whitelistValidation":"property flowType should not exist"
}
},
{
"target":{
"drainPointType":"roundsurface",
"flowType":"normal",
"flowCoefficient":0.5,
"point":{
"x":0,
"y":0
}
},
"value":0.5,
"property":"flowCoefficient",
"constraints":{
"whitelistValidation":"property flowCoefficient should not exist"
}
},
{
"target":{
"drainPointType":"roundsurface",
"flowType":"normal",
"flowCoefficient":0.5,
"point":{
"x":0,
"y":0
}
},
"value":{
"x":0,
"y":0
},
"property":"point",
"constraints":{
"whitelistValidation":"property point should not exist"
}
}
]
}
]
}
]
包含数组的DTO对象:
export class CreateDrainPointDTO extends DTO {
@IsArray()
@IsNotEmpty()
@ArrayMinSize(1)
@ValidateNested({ each: true })
@Type(() => DrainPointDTO)
drainPoints: DrainPoint[]
}
对象本身:
export class DrainPointDTO {
@IsString()
@IsOptional()
uuid: string
@IsEnum(DrainPointType)
@IsNotEmpty()
drainPointType: DrainPointType
@IsEnum(DrainPointflowType)
@IsNotEmpty()
flowType: DrainPointflowType
@IsArray()
@IsNotEmpty()
point: Point
@IsNumber()
@IsOptional()
flowCoefficient: number
}
我的自定义DTO抽象类:
export abstract class DTO {
static async factory<T extends DTO>(Class: new () => T, partial: Partial<T>): Promise<T> {
const dto = Object.assign(new Class(), partial)
const errors = await validate(dto, { whitelist: true, forbidNonWhitelisted: true })
if (errors.length > 0) {
throw new CustomError()
.withError('invalid_parameters')
.withValidationErrors(errors)
}
return dto
}
}
我使用这个DTO抽象类是为了有一种干净的方法来判断控制器内部的主体:
async createDrainPoint (req: Request, res: Response): Promise<void> {
const dto = await DTO.factory(CreateDrainPointDTO, req.body as Partial<CreateDrainPointDTO>)
const drainPoints = await this.drainPointService.create(dto)
res.status(201).json(DrainPointTransformer.array(drainPoints))
}