我找到的所有示例都有一个 query
顶级对象,然后是一个查询列表,然后返回更深入的类型 .
由于我有大量的查询,我想将它们分组,这是我尝试过的:
const AppType = new GraphQLObjectType({
name: 'App',
description: 'Generic App Details',
fields: () => ({
name: { type: GraphQLString },
appId: { type: GraphQLInt },
}),
});
const MyFirstQuery = {
type: new GraphQLList(AppType),
args: {
appId: { type: GraphQLInt },
},
resolve: (root, args) => fetchApp(args.appId),
};
/* snip MySecondQuery, MyThirdQuery, MyFourthQuery */
const MyFirstGroupQuery = new GraphQLObjectType({
name: 'myFirstGroup',
description: 'the first group of queries',
fields: () => ({
myFirstQuery: MyFirstQuery,
mySecondQuery: MySecondQuery,
myThirdQuery: MyThirdQuery,
myFourthQuery: MyFourthQuery,
}),
});
/* snip MySecondGroupQuery, MyThirdGroupQuery and their types */
const QueryType = new GraphQLObjectType({
name: 'query',
description: 'read-only query',
fields: () => ({
myFirstGroup: MyFirstGroupQuery,
mySecondGroup: MySecondGroupQuery,
myThirdGroup: MyThirdGroupQuery,
}),
});
const Schema = new GraphQLSchema({
query: QueryType,
});
为什么我不能像 QueryType
那样制作更多的嵌套级别?如果我将所有查询都放在 QueryType
中,但代码工作正常,但我的 MyFirstGroupQuery
会产生错误:
Error: query.myFirstGroup field type must be Output Type but got: undefined.
我如何实现我想要的?我真的不想只是为我的所有查询添加前缀 .
1 回答
错误
query.myFirstGroup field type must be Output Type but got: undefined.
表示您没有提供myFirstGroup
的类型,您必须使用type
字段提供类型myFirstGroup: { type: MyFirstGroupQuery, resolve: () => MyFirstGroupQuery, },
并且如果类型
MyFirstGroupQuery
每个字段必须具有type
定义,例如GraphQLInt
,GraphQLString
,GraphQLID
,即使它是自定义类型如MyFirstGroupQuery
在
GraphQLSchema
构造函数中,你提供的RootQuery
是QueryType
,它是GraphQLSchema
它只接受带有GraphQLObjectType
的rootQuery
,其字段必须定义type
GraphQL是严格基于类型的,您声明的每个字段都必须定义
type
https://github.com/graphql/graphql-js
https://github.com/graphql/graphql-js/blob/master/src/type/schema.js#L32
GraphiQL