typescript - ใช้ class-validator ตรวจสอบวัตถุซ้อนตามคุณสมบัติของพาเรนต์
มีวิธีใดที่จะทำให้ฟิลด์ในอ็อบเจ็กต์ลูกถูกตรวจสอบตามคุณสมบัติของอ็อบเจ็กต์แม่หรือไม่ อ็อบเจ็กต์ต่อไปนี้แสดงโครงสร้างที่เรากำลังพยายามตรวจสอบความถูกต้อง ตัวอย่างเช่น ในโครงสร้างต่อไปนี้ จะมีเฉพาะ first.name ที่ไม่จำเป็นเมื่อ id และ dateOfBirth (dob) ถูกกำหนดแล้วหรือไม่?
@InputType()
export class GetEligibilityArgs {
@Field((type) => NameInput)
@ValidateNested()
@Type(() => NameInput)
name: NameInput;
@Field({ nullable: true })
@ValidateIf((o: GetEligibilityArgs) => {
return !(o.name?.first && o.name?.last && o.dateOfBirth);
})
@IsNotEmpty({ message: 'id is required' })
id?: string;
@Field({ nullable: true })
@ValidateIf((o: GetEligibilityArgs) => { // <-- not sure if this is the correct way to do this
return !(o.id && o.name?.first && o.name?.last);
})
@IsNotEmpty()
dateOfBirth?: string;
}
วัตถุซ้อน
@InputType()
export class NameInput {
@Field({ nullable: true })
@IsNotEmpty()
first?: string;
@Field({ nullable: true })
@IsNotEmpty()
last?: string;
}
อินพุตที่ถูกต้อง
- รหัส, ชื่อ.ชื่อจริง, ชื่อ.นามสกุล
- รหัส, ชื่อ.ชื่อแรก, วันเกิด
- รหัส, นามสกุล, วันเกิด
- ชื่อ.ชื่อจริง, ชื่อ.นามสกุล, วันเดือนปีเกิด
สิ่งอื่นทั้งหมดจะถือว่าไม่ถูกต้อง
คำตอบ #1
นี่คือวิธีแก้ปัญหาที่ฉันคิดขึ้นมา กรุณาแจ้งให้ฉันทราบหากมีวิธีที่ดีกว่านี้
ข้อจำกัดตัวตรวจสอบแบบกำหนดเอง
@ValidatorConstraint()
export class GetEligibilityCriteriaConstraint implements ValidatorConstraintInterface {
validate(
{ id, name, dateOfBirth }: GetEligibilityArgs,
validationArguments: ValidationArguments,
) {
if (id && name?.first && name?.last) {
return true;
}
if (id && name?.first && dateOfBirth) {
return true;
}
if (id && name?.last && dateOfBirth) {
return true;
}
if (name?.first && name?.last && dateOfBirth) {
return true;
}
return false;
}
defaultMessage(args: ValidationArguments) {
return 'Eligibility requires 3 of the following 4 fields (id, name.first, name.last, dateOfBirth';
}
}
คลาส Wrapper เกณฑ์คุณสมบัติใช้สำหรับตรวจสอบวัตถุ
@ArgsType()
export class GetEligibilityCriteria {
@Field((type) => GetEligibilityArgs)
@Validate(GetEligibilityCriteriaConstraint)
@Type(() => GetEligibilityArgs)
@ValidateNested()
criteria: GetEligibilityArgs;
}
จากนั้นสิ่งนี้จะถูกนำไปใช้ในคำสืบค้นตัวแก้ปัญหาเช่นนี้
@Query((returns) => Eligibility)
eligibility(@Args() { criteria }: GetEligibilityCriteria) {
// performs some mapping and calls service
}
ข้อจำกัดของตัวตรวจสอบมาตรฐานถูกนำมาใช้กับคลาส GetEligibilityArgs
