简体   繁体   中英

Provide explicit type for the mutation GraphQL

I'm trying to create a mutation which will accept list of products. But doing so GraphQL is throwing error for createMultipleProducts method. Not sure what is the mistake here.

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 {}
  }
}

I'm getting this error:

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

There is a need to inform GraphQL the type of the arguments explicitly if it is a complex object array.

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

New format 2022

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM