在GraphQL中,我们可以使用类验证器装饰器来比较类型中的字段。以下是一个使用TypeScript和class-validator
库的示例,该库提供了许多内置的验证装饰器,以及如何创建自定义装饰器来比较字段。
GraphQL: 是一种用于API的查询语言,它允许客户端请求所需的数据结构。
类验证器装饰器: 是一种特殊类型的装饰器,用于在类字段上添加元数据,以便在运行时进行验证。
TypeScript: 是JavaScript的一个超集,添加了静态类型等特性,使得代码更易于维护和调试。
假设我们有一个GraphQL输入类型,需要验证两个字段startDate
和endDate
,确保startDate
早于endDate
。
import { IsDate, ValidateIf, IsDateString } from 'class-validator';
import { InputType, Field } from '@nestjs/graphql';
@InputType()
export class DateRangeInput {
@Field()
@IsDate()
startDate: Date;
@Field()
@IsDateString()
@ValidateIf((o) => o.startDate)
endDate: string;
// 自定义验证器装饰器
@ValidateIf((o) => o.startDate && o.endDate)
@IsBefore('startDate')
endDateBeforeStartDate() {}
}
// 自定义装饰器工厂函数
export function IsBefore(property: string) {
return function (object: Object, propertyName: string) {
registerDecorator({
name: 'isBefore',
target: object.constructor,
propertyName: propertyName,
constraints: [property],
validator: {
validate(value: any, args: ValidationArguments) {
const [relatedPropertyName] = args.constraints;
const relatedValue = (args.object as any)[relatedPropertyName];
if (new Date(value) >= new Date(relatedValue)) {
throw new Error(`${propertyName} must be before ${relatedPropertyName}`);
}
return true;
},
},
});
};
}
如果在使用上述代码时遇到问题,比如验证不通过或者装饰器没有按预期工作,可以检查以下几点:
npm install class-validator @nestjs/graphql
。这种验证逻辑在处理日期范围、价格范围、数值比较等场景中非常有用。例如,在电商应用中验证订单的创建日期不能晚于当前日期,或者在金融应用中验证贷款的结束日期必须晚于开始日期。
通过这种方式,我们可以确保GraphQL API接收到的数据是有效和符合预期的,从而提高应用的健壮性和用户体验。
领取专属 10元无门槛券
手把手带您无忧上云