【问题标题】:NestJS GrapHQL ensure scalar typeNestJS GraphQL 确保标量类型
【发布时间】:2021-05-14 09:02:22
【问题描述】:

我的用户 ID CustomerIDProviderID 有自定义标量,我想在有人调用突变时验证它们以确保给定 ID 与用户匹配并且类型正确。

我们无法使 CustomerScalar parseValue 方法异步,所以我正在寻找一种处理此类事情的好方法。

也许是 customerDecorator ?我不知道 ?任何想法 ? 我想使用依赖注入访问我的存储库,以确保传递的 ID 存在于数据库中并且确实是客户。 Field Middleware and Directive似乎不支持Deps注入。

@InputType()
export class CreateBillInput {
  @Field(() => CustomerIDScalar)
  customerID: CustomerID;

  @Field()
  name: string;

  @Field(() => Int)
  amount: number;
}

我想要的却行不通:

@Injectable()
export class CustomerIDScalar implements CustomScalar<string, CustomerID> {
  constructor(private userRepository: IUserRepository) {}

  parseValue(value: string) {
    return this.getCustomerID(value);
  }

  parseLiteral(ast: ValueNode) {
    if (ast.kind !== Kind.STRING) {
      throw new TypeError('Argument is not a string value.');
    }

    return this.getCustomerID(value);;
  }

  serialize(value: CustomerID) {
    return value.value; // value sent to the client
  }

  // TODO: Not usable here
  private async getCustomerID(userID: string): Promise<CustomerID> {
    const user = await this.userRepository.getByID(userID);

    if (!user || !user.isCustomer()) {
      throw new BadRequestException('There is no such customer user for provided ID.');
    }

    return user.id as CustomerID;
  }
}

谢谢

【问题讨论】:

    标签: graphql nestjs


    【解决方案1】:

    首先。 gql 标量验证是关于验证所有数据是否正确的技术检查(模式检查)。它不应该有任何业务规则验证的东西。

    要达到预期的结果,您可以使用以下内容:

    1. 用@Args 装饰器嵌套validation pipes

      @Mutation(返回 => 组) 异步创建组( @Args('组',新的 ValidationPipe()) 输入:创建组输入, )

    2. 类验证https://github.com/typestack/class-validator

    3. 只需为输入类型放置一个常规 ID/Int 标量并稍后在响应此类操作的服务类中对其进行验证(建议在 gql 中对此类事情使用此方法)

    【讨论】:

      猜你喜欢
      • 2021-05-30
      • 2019-09-29
      • 2022-07-02
      • 2021-02-20
      • 2022-08-05
      • 2018-09-28
      • 1970-01-01
      • 2021-06-23
      相关资源
      最近更新 更多