[英]How to make one of two fields required in Nestjs DTO with its proper API documentation?
例如:
{
phone: string
email: string
....
....
otherFields
....
....
}
請求正文中應要求電話或email 。 我找到了僅用於驗證的解決方案,這里是:
export class MyDto {
@IsString()
@ValidateIf((obj, value) => !obj.email || value)
phone: string;
@IsString()
@ValidateIf((obj, value) => !obj.phone || value)
phone: string;
..... other fields .....
}
但是,如何為此申請 swagger 文檔? OAS3 文檔中有 oneOf 和 anyOf。 這是 swagger 方面的合適解決方案: 鏈接
如何同時實施驗證和 swagger 文檔?
我看到你的問題的唯一選擇是這個。
export class EmailDto {
@ApiProperty()
@IsString()
email: string;
}
export class PhoneDto {
@ApiProperty()
@IsString()
phone: string;
}
export class CreateCatDto {
@ApiProperty({
oneOf: [
{
type: 'object',
required: ['phoneNumber'],
properties: {
phoneNumber: { type: 'string' },
},
},
{
type: 'object',
required: ['email'],
properties: { email: { type: 'string' } },
},
],
})
@ValidateNested()
@Type((type) => (type.object.phoneOrEmail.email ? EmailDto : PhoneDto))
phoneOrEmail: PhoneDto | EmailDto;
}
在這里你有 NestJs 中anyOf的文檔我沒有使用getSchemaPath
因為我的模式沒有被 Swagger 初始化所以我在@ApiProperty
中手動創建我的模式
對於class-validator
,我要求使用@ValidateNested()
和@Type()
驗證正確類型的 DTO。
問題是。 如果他們向您發送了 email 和 phoneNumber class-validator
,則只會驗證 email,因為:
(type.object.phoneOrEmail.email? EmailDto: PhoneDto)
如果有 email,它將首先驗證 class EmailDto。 所以你需要判斷是否有 Email 和 PhoneNumber 你需要用兩者驗證 DTO。
Go 在 Google 上檢查是否有類似class-validaor
的 anyOf
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.