TypeGraphql字段和Arg装饰器使用自定义类型



我试图使用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.

我还尝试定义一个输入类:

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?

@InputType代替@ObjectType也没有帮助。如何正确定义@Field@Arg等装饰剂?

任何帮助都是感激的。谢谢。

我认为你想要的是一个包含数字和字符串的数组在这种情况下你应该使用

@InputType()
class HitsInput
{
@Field()
Hits: [number | string];
}
@Resolver()
export default class SearchResolver {
@Query(() => [String], { nullable: true })
async searchAssetList(@Arg('input') input: HitsInput) {
return []
}
}

如果不是这种情况而你想要一个带有动态字段的对象你需要定义对象,比如如果hits有Name和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 []
}
}

,如果你想在用户请求中有一个动态参数库,我不太确定这是可能的,但这是可能的

@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
});

在你的类中,你可以像这样使用你的customtype:

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

最新更新