首页 > 解决方案 > 如果字段可以为空,则验证期间的装饰器仍然有效

问题描述

我使用类验证器。但是在阅读了这个包的文档之后graphql,总的来说,我仍然没有找到如何解决这个问题

有这个突变:

@Mutation(() => UserEntity)
  async updateUserById(
    @Args('id') id: string,
    @Args('inputs') inputs: UpdateUserDto
  )
    : Promise<UserEntity> {
    return await this.userService.updateUserById(id, inputs)
  }

我的 Dto 看起来像:

@InputType()
export class UpdateUserDto {

  @Field({nullable: true})
  @IsString()
  fullName?: string;

  @Field({nullable: true})
  @IsEmail()
  @IsString()
  email?: string;

  @Field({nullable: true, description: 'Password must be longer than or equal to 5 characters'})
  @MinLength(5)
  @IsString()
  password?: string;

  @Field({nullable: true})
  @IsString()
  phoneNumber?: string
}

当我想更新一个字段时:

mutation{
  updateUserById(id:"847025d8-0e6f-4456-88f7-710b104db6ca", 
    inputs:{
    fullName:"New name"
  })
  {
    fullName
  }
}

即使该字段可以为空,仍然会从工作装饰器中收到错误:

"errors": [
    {
      "message": {
        "statusCode": 400,
        "error": "Bad Request",
        "message": [
          {
            "target": {
              "fullName": "New name"
            },
            "constraints": {
              "isString": "email must be a string",
              "isEmail": "email must be an email"
            }
          },

如何解决?

标签: node.jsgraphqlnestjs

解决方案


通过添加@IsOptional()装饰器解决


推荐阅读