我创建了3个DTO,它们从另一个父DTO扩展而来,然后在控制器中,我使用class-validator库来验证用户传递给控制器的数据。
parent.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
controller.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,
});
}
}
答案 0 :(得分:0)
对于您而言,我只建议实现一个IParent
接口并将其扩展到您的Parent
类中。
然后,您可以在控制器中使用IParent
,如下所示:
@UsePipes(ValidationPipe)
@Post()
async createItem(@Res() res, @Body() body: IParent) {
const result = await this.createTest.createObject(body);
return res.status(HttpStatus.OK).json({
message: 'Item has been created successfully',
newLicense,
});
}
export interface IParent {
platform: string;
admins: string[];
purchaseDate: Date;
validFrom: Date;
validTo: Date;
}
import { IsNotEmpty, IsString, IsDateString, IsMongoId } from 'class-validator';
export class Parent implements IParent {
@IsNotEmpty()
@IsMongoId()
platform: string;
@IsNotEmpty()
@IsString({ each: true })
admins: string[];
@IsDateString()
purchaseDate: Date;
@IsDateString()
validFrom: Date;
@IsDateString()
validTo: Date;
}
让我知道是否有帮助;如果是这样,请验证答案,否则,请提供复制量最少的存储库链接,以便我们提供进一步的帮助。