使用自定义类型的 TypeGraphql Field 和 Arg 装饰器

TypeGraphql Field and Arg decorators using custom type

我正在尝试使用 type-graphql 库构建解析器,但发现无法定义自定义参数类型。这是我的代码:


type Hits = { [K: string]: string | number }

@Resolver()
export default class SearchResolver {
  @Query(() => [String], { nullable: true })
  @UseMiddleware(isAuthenticated)
  async searchAssetList(@Arg('hits') hits: Hits) {
    return [];
  }
}

我收到一个错误:

NoExplicitTypeError: Unable to infer GraphQL type from TypeScript reflection system. You need to provide explicit type for argument named 'hits' of 'searchAssetList' of 'SearchResolver' class.

我也尝试定义一个输入 class:

type Hits = { [K: string]: string | number }

@ObjectType()
class SearchListInput {
  @Field(() => GraphQLObjectType)
  hits: Hits;
}

@Resolver()
export default class SearchResolver {
  @Query(() => [String], { nullable: true })
  async searchAssetList(@Arg('input') input: SearchListInput) {
    return []
  }
}

又遇到一个错误:

UnhandledPromiseRejectionWarning: Error: Cannot determine GraphQL input type for argument named 'input' of 'searchAssetList' of 'SearchResolver' class. Is the value, that is used as its TS type or explicit type, decorated with a proper decorator or is it a proper input value?

@ObjectType 替换为 @InputType 也无济于事。如何正确定义@Field@Arg等装饰器?

感谢任何帮助。谢谢。

我认为您正在尝试使用包含数字和字符串的数组 Arg,在这种情况下您应该这样做

@InputType()
class HitsInput
{
    @Field()
    Hits: [number | string];
}

@Resolver()
export default class SearchResolver {
  @Query(() => [String], { nullable: true })
  async searchAssetList(@Arg('input') input: HitsInput) {
    return []
  }
}

如果不是这种情况,并且您想要一个带有动态字段的对象,则需要定义该对象,假设命中是否具有名称和 Id_Hits、

@InputType()
class HitsInput
{
    @Field()
    Id_Hits: number;

    @Field()
    Name: string;
}

@Resolver()
export default class SearchResolver {
  @Query(() => [String], { nullable: true })
  async searchAssetList(@Arg('input') input: HitsInput) {
    return []
  }
}

如果你想在用户请求中有一个动态 args 基础,我不太确定这是否可能,但这样做是可能的

@InputType()
class HitsInput
{
    [key: string]: any;
}

几天前我遇到了完全相同的问题,我通过创建自己的自定义类型使用 GraphQLScalarType 解决了这个问题 在这里如何做

import { GraphQLScalarType} from "graphql";

export const GraphQLAny = new GraphQLScalarType({
    name: 'Any',
    serialize: (value) => value,
    parseValue: (value) => value,
    parseLiteral: (ast) => ast
});

并且在您的 class 中,您可以像这样使用您的 customTpe:

@ObjectType()
class SearchListInput {
  @Field(() => GraphQLAny)
  hits: typeof GraphQLAny;
}