我创建了 3 个从另一个父 DTO 扩展的 DTO,然后在控制器中我使用类验证器库来验证用户传递给控制器的数据。
父.dto.ts
import { IsNotEmpty, IsString, IsDateString, IsMongoId } from 'class-validator';
export class Parent {
@IsNotEmpty()
@IsMongoId()
platform: string;
@IsNotEmpty()
@IsString({ each: true })
admins: string[];
@IsDateString()
purchaseDate: Date;
@IsDateString()
validFrom: Date;
@IsDateString()
validTo: Date;
}
a.dto.ts
import { IsMongoId, IsNotEmpty, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
import { Parent } from './parent.dto';
class A_options {
@IsNotEmpty()
@IsMongoId()
dataA: string;
}
export class A extends Parent {
@IsNotEmpty()
testA: string;
@ValidateNested()
@Type(() => A_options)
data: A_options;
}
b.dto.ts
import { IsMongoId, IsNotEmpty, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
import { Parent } from './parent.dto';
class B_options {
@IsNotEmpty()
@IsMongoId()
dataB: string;
}
export class B extends Parent {
@IsNotEmpty()
testB: string;
@ValidateNested()
@Type(() => B_options)
data: B_options;
}
c.dto.ts
import { IsMongoId, IsNotEmpty, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
import { Parent } from './parent.dto';
class C_options {
@IsNotEmpty()
@IsMongoId()
dataC: string;
}
export class C extends Parent {
@IsNotEmpty()
testC: string;
@ValidateNested()
@Type(() => C_options)
data: C_options;
}
在控制器中我正在使用ValidationPipe
设置body: A
控制器.ts
@UsePipes(ValidationPipe)
@Post()
async createItem(@Res() res, @Body() body: A) {
const result = await this.createTest.createObject(body);
return res.status(HttpStatus.OK).json({
message: 'Item has been created successfully',
newLicense,
});
}
}
这也适用于body: B
和body: C
但是当我这样做时它不起作用body: A | B | C
我怎样才能让它工作,所以代码会是这样的?
@UsePipes(ValidationPipe)
@Post()
async createItem(@Res() res, @Body() body: A | B | C) {
const result = await this.createTest.createObject(body);
return res.status(HttpStatus.OK).json({
message: 'Item has been created successfully',
newLicense,
});
}
}