0

我有这个input用于更新块。我希望用户可以更新名称或内容或两者。现在的问题是,如果我只传递名称 GrapQL 会抛出一个错误Variable \"$updateBlockInput\" got invalid value { name: \"Updated again\" }; Field content of required type String! was not provided.,例如 varsa。

我究竟做错了什么?


更新块.input.ts

import { InputType, Field } from '@nestjs/graphql';
import { IsOptional, IsNotEmpty } from 'class-validator';

@InputType()
export class UpdateBlockInput {
  @IsOptional()
  @IsNotEmpty()
  @Field()
  name?: string;

  @IsOptional()
  @IsNotEmpty()
  @Field()
  content?: string;
}

块解析器.ts

...
@Mutation(returns => BlockType)
updateBlock(
  @Args('id') id: string,
  @Args('updateBlockInput') updateBlockInput: UpdateBlockInput,
) {
  return this.blockService.update(id, updateBlockInput);
}
...

突变

mutation(
  $id: String!
  $updateBlockInput: UpdateBlockInput!
) {
  updateBlock(
    id: $id
    updateBlockInput: $updateBlockInput
  ) {
    name
    content
  }
}

变量

{
  "id": "087e7c12-b48f-4ac4-ae76-1b9a96bbcbdc",
  "updateBlockInput": {
    "name": "Updated again"
  }
}
4

1 回答 1

2

如果它们是可选的,那么你需要避免IsNotEmpty和替换是IsString说如果值存在,它必须是字符串类型。

如果您想接受其中任何一个并且在发送 non 时失败,您需要编写自己的自定义验证器,因为这种情况不支持开箱即用。

一个例子:

import {ValidatorConstraint, ValidatorConstraintInterface} from 'class-validator';
@ValidatorConstraint({async: false})
export class IsInPast implements ValidatorConstraintInterface {
    public validate(value: unknown): boolean {
        if (typeof value !== 'string' && typeof value !== 'number') {
            return false;
        }
        const now = new Date();
        now.setHours(23);
        now.setMinutes(59);
        now.setSeconds(59);
        now.setMilliseconds(999);
        return `${value}`.match(/^\d+$/) !== null && `${value}` <= `${now.getTime()}`;
    }

    public defaultMessage(): string {
        return 'Should be in past';
    }
}

稍后在代码中的某个地方:

@Validate(IsInPast)
public dateField: string;
于 2020-04-08T08:21:54.977 回答