为突变 GraphQL 提供显式类型

Posted

技术标签:

【中文标题】为突变 GraphQL 提供显式类型【英文标题】:Provide explicit type for the mutation GraphQL 【发布时间】:2021-08-20 04:49:12 【问题描述】:

我正在尝试创建一个接受产品列表的突变。但是这样做 GraphQL 会为 createMultipleProducts 方法抛出错误。不知道这里有什么错误。

import  Inject  from "@nestjs/common";
import  Args, Mutation, Query, Resolver  from "@nestjs/graphql";
import  ClientProxy  from "@nestjs/microservices";
import  ProductRequest  from "src/types/ms-product/product.request.type";
import  ProductResponse  from "src/types/ms-product/product.response.type";
@Resolver(of => ProductResponse)
export class ProductResolver 

  constructor(
    @Inject('SERVICE__PRODUCT') private readonly clientServiceProduct: ClientProxy
  ) 

  @Mutation(returns => ProductResponse)
  async createProduct(@Args('data') product: ProductRequest): Promise<ProductResponse> 
    const PATTERN = cmd: 'ms-product-create';
    const PAYLOAD = product;
    return this.clientServiceProduct.send(PATTERN, PAYLOAD)
    .toPromise()
    .then((response: ProductResponse) => 
      return response;
    )
    .catch((error) => 
      return error;
    )
  

  @Mutation(returns => [ProductResponse])
  async createMultipleProducts(@Args('data') products: [ProductRequest]): Promise<Array<ProductResponse>> 
    try 
      const PROMISES = products.map(async (product: ProductRequest) => 
        const PATTERN = cmd: 'ms-product-create';
        const PAYLOAD = product;
        return await this.clientServiceProduct.send(PATTERN, PAYLOAD).toPromise();
      );
  
      return await Promise.all(PROMISES);
     catch (error) 
      throw new Error(error);
    
  

  @Query(returns => ProductResponse)
  async readProduct(@Args('data') id: string) 
    return 
  

我收到此错误:

UnhandledPromiseRejectionWarning: Error: Undefined type error. Make sure you are providing an explicit type for the "createMultipleProducts" (parameter at index [0]) of the "ProductResolver" class.

【问题讨论】:

【参考方案1】:

如果它是一个复杂的对象数组,则需要明确告知 GraphQL 参数的类型。

@Mutation(returns => [ProductResponse])
async createMultipleProducts(@Args( name: 'data', type: () => [ProductRequest] ) products: ProductRequest[]): Promise<Array<ProductResponse>> 
  ...

【讨论】:

以上是关于为突变 GraphQL 提供显式类型的主要内容,如果未能解决你的问题,请参考以下文章

Flutter / GraphQL - 以自定义类型为参数的突变

在 GraphQL 中的相关类型之间创建突变

从另一个突变中调用 GraphQL 突变?

如何在 django-graphql-auth 中使用自定义注册突变

AWS放大graphql突变:不能为不可为空的字段返回null

如何修复 graphql 突变类型名错误