我有一个创建 Controller ,它在 PG 数据库中执行 CRUD 之前对 JSON 数据进行严格的验证。 我正在尝试实现多种类型之一的验证。
Controller 路由
async create(@Body() newSheet: CreateSheetsDto) {
return this.sheetService.create(newSheet);
}
DTO
import { ApiProperty } from '@nestjs/swagger';
import {ValidateNested} from "class-validator";
import { Type } from 'class-transformer';
import { BodyValidator} from "../validators/BodyValidator";
export class CreateSheetsDto { })
@ValidateNested({ each: true })
@Type(() => BodyValidator)
readonly body: BodyValidator;
}
在多个子键上有多层 JSON 验证。 我尝试在 @Type 回调中使用 OR 运算符,相当直观。结果不起作用
export class CreateSheetsDto { //test
@ApiProperty({ type: BodyValidator || TypeTwoValidator })
@ValidateNested({ each: true })
@Type(() => BodyValidator || TypeTwoValidator)
readonly body: BodyValidator | TypeTwoValidator;
}
我还尝试在 Controller 中使用联合运算符,并创建另一个特定于另一种类型的 DTO,例如:
async create(@Body() newSheet: CreateSheetsDto | CreateSheetsTypeTwoDto) {
return this.sheetService.create(newSheet);
}
这也不起作用。 我认为我的做法不对,但我也无法在网上找到太多相关信息,您可以提供任何建议吗?
最佳答案
这与类转换器包有关。您可以通过定义鉴别器来存档它,如下所述:https://github.com/typestack/class-transformer#providing-more-than-one-type-option
示例:
export class Album {
id: number;
name: string;
@Type(() => Photo, {
discriminator: {
property: '__type',
subTypes: [
{ value: Landscape, name: 'landscape' },
{ value: Portrait, name: 'portrait' },
{ value: UnderWater, name: 'underwater' },
],
},
})
topPhoto: Landscape | Portrait | UnderWater;
}
关于api - NestJS API 接受请求正文中的一种或其他类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62556649/