gpt4 book ai didi

typescript - 在 NestJS 中使用与 GraphQL 中的 Input 和 Object 类型相同的类

转载 作者:行者123 更新时间:2023-12-03 13:59:07 24 4
gpt4 key购买 nike

我正在尝试设置我的 graphql resover 来处理一组对象,但无法配置 @Args 装饰器。
我创建了自己的 ArgsType

import { ArgsType, Field, Int, ObjectType } from '@nestjs/graphql';

@ArgsType()  // to be used as type in the resolver
@ObjectType()  // for schema generation 
export class Club {
 @Field(type => String)
president: string;

 @Field(type => Int)
members?: number;
}
添加单个俱乐部的解析器工作得很好!
 @Query(() => Int)
async addClub(@Args() club: Club) {
// handle stuff
  }
但是如果我想给一个这样的俱乐部数组
 @Query(() => Int)
async addClubs(@Args({name: 'clubs', type: () => [Club]}) clubs: Array<Club>) {
// handle stuff
  }
嵌套启动时出现错误
 UnhandledPromiseRejectionWarning: Error: Cannot determine a GraphQL input type for the "clubs". Make sure your class is decorated with an appropriate decorator.
虽然我可以使用这样的字符串数组
 @Query(() => [String])
async addStrings(@Args({ name: 'clubs', type: () => [String], }) clubs: Array<string>) {
// handle stuff
  }
我很确定应该有一个简单的解决方案,但无法弄清楚从这里去哪里。

最佳答案

根据错误,

Cannot determine a GraphQL input type for the "clubs". Make sure your class is decorated with an appropriate decorator
您正在尝试使用 Club类作为 GraphQL 输入类型,而它已经是对象类型(根据您使用的 @ObjectType 注释)。

解决方案一:
我建议您编写一个单独的 GraphQL 输入类型,如下所示(未测试)。如果您需要分开处理 Club 的输入和输出的方式,这会更简洁且耦合更少。 .
import { InputType, Field } from '@nestjs/graphql';

@InputType()
export class ClubInput {
@Field()
president: string;

@Field()
members?: number;
}
然后在你的解析器中,你可以像下面这样使用它。
@Query(() => Int)
async addClubs(@Args({name: 'clubs', type: () => [ClubInput]}) clubs: Array<ClubInput>) {
// handle stuff
}

方案二:
但是如果你真的需要为这两个目的使用同一个类,你可以尝试使用相同的 Club 创建输入和对象类型。姓名。默认情况下,对象类型的名称是类的名称。因此,您需要明确提供名称以避免冲突。
import { Field, Int, ObjectType, InputType } from '@nestjs/graphql';

@InputType("ClubInput")
@ObjectType("ClubType")
export class Club {
@Field(type => String)
president: string;

@Field(type => Int)
members?: number;
}
现在您的 Club输入和对象类型有不同的名称。然后在你的解析器中,你可以像下面这样使用它。
@Query(() => Int)
async addClubs(@Args({name: 'clubs', type: () => [ClubInput]}) clubs: Array<ClubInput>) {
// handle stuff
}
注:在此解决方案中,您需要确保 Club永远不会包含表达循环引用或对接口(interface)和联合的引用的字段。如果发生这种情况,您将不得不转到解决方案 1,否则这将使您的输入引发错误。

要点是在 Typescript GraphQL 中, InputTypeObjectType是两个不同的概念,我们需要正确使用它以避免任何问题。

关于typescript - 在 NestJS 中使用与 GraphQL 中的 Input 和 Object 类型相同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64607530/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com