[英]How to create custom field validation decorators in NestJS with GraphQL
I'm working on a NestJS API with apollo-server-express and I have the next InputType for appointments:我正在使用 apollo-server-express 开发 NestJS API,我有下一个 InputType 用于约会:
@InputType()
export class AppointmentInput {
@Field(of => String)
@IsNotEmpty()
name: string;
@Field(of => String)
@IsNotEmpty()
@IsDateString()
dateStart: string;
@Field(of => String)
@IsNotEmpty()
@IsDateString()
dateEnd: string;
@Field(of => Boolean)
@IsBoolean()
paid: boolean;
@Field(of => Int)
idDoctor: number;
@Field(of => Int)
idPatient: number;
@Field(of => Int)
idService: number;
}
Let's say I want to validate if the name has some "a" letter with a Pipe:假设我想验证该名称是否有一些带有 Pipe 的“a”字母:
import { PipeTransform, Injectable, ArgumentMetadata, HttpException, HttpStatus } from '@nestjs/common';
@Injectable()
export class NamePipe implements PipeTransform<string, string>{
transform(name: string, metadata: ArgumentMetadata) {
if (name.includes('a')) {
throw new HttpException('The name has an a', HttpStatus.BAD_REQUEST);
}
return name;
}
}
But if use it like this:但是如果像这样使用它:
@Field(of => String)
@IsNotEmpty()
@UsePipes(NamePipe)
name: string;
It throws me the next error:它抛出下一个错误:
The return type of a property decorator function must be either 'void' or 'any'.
属性装饰器 function 的返回类型必须是“void”或“any”。 Unable to resolve signature of property decorator when called as an expression.
当作为表达式调用时,无法解析属性装饰器的签名。 Type 'TypedPropertyDescriptor' is not assignable to type 'void'.
类型“TypedPropertyDescriptor”不可分配给类型“void”。
How can I solve this and use custom decorators to validate my fields?我该如何解决这个问题并使用自定义装饰器来验证我的字段? Also is important that my decorators can call services, because maybe in the future I want to validate for example the role id, and check if in the database exists a role with that id and if not throw an error.
我的装饰器可以调用服务也很重要,因为也许将来我想验证例如角色 ID,并检查数据库中是否存在具有该 ID 的角色,如果不存在则抛出错误。
I think you should rather create a custom class-validator decorator and use it like any class-validator decorator, assuming you've already applied a global NestJS validation pipe我认为您应该创建一个自定义类验证器装饰器并像使用任何类验证器装饰器一样使用它,假设您已经应用了全局 NestJS 验证 pipe
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.