我正在尝试为我的查询创建树状结构,以摆脱像我这样的查询
peopleList, peopleSingle, peopleEdit, peopleAdd, peopleDelete companyList, companySingle, companyEdit, companyAdd, companyDelete etc.
最后我想发送这样的查询:
query test { people { list { id name } single(id: 123) { id name } } company { list { id name } single(id: 456) { id name } } } mutation test2 { people { create(data: $var) { id name } } people { edit(id: 123, data: $var) { id name } } }
这是我的人员模块上的查询对象的一部分:
people: { type: //What type this should be? name: 'Root of People queries', fields: () => ({ list: { type: peopleType, description: 'Returns all people in DB.', resolve: () => { // resolve method implementation } }, single: { type: peopleType, description: 'Single row from people table. Requires ID argument.', args: { id: { type: new GraphQLNonNull(GraphQLID) } }, resolve: () => { // resolve method implementation } } }) }
我试图将这个片段放入GraphQLObjectType,然后在RootQuery中将它们组合在一起(再次使用GraphQLObjectType) - 不起作用.
替代方法可以是创建新类型 - 类似peopleQueriesType,在此类型中将所有查询指定为字段,然后为此对象创建单个查询.但这对我来说似乎很奇怪 - 用不必要的对象污染我的代码只是为了将我的查询合并成树状.
我试图看看Apollo服务器实现,如果它可以做这种查询结构,但在文档中找不到任何帮助.
我在我的服务器上使用node.js + express + graphql-js.
简答:
type应该GraphQLObjectType
包含所有这样的字段:
type: new GraphQLObjectType({ name: 'patientQuery', fields: { find, findOne } })
详细信息:我最终使用以下代码进行了此查询:
{ patient { find { id active } findOne(id: "pat3") { id active } } }
在patient/queries/index.js
我有这个
import findOne from './find-one.js'; import find from './find.js'; import { GraphQLObjectType } from 'graphql'; export default { patient: { type: new GraphQLObjectType({ name: 'patientQuery', fields: { find, findOne } }), resolve(root, params, context, ast) { return true; } } };
然后在 queries.js
import patient from './patient/queries/index.js'; export default { ...patient };
最后我的架构schema.js
传递给graphql express服务器
import { GraphQLObjectType, GraphQLSchema } from 'graphql'; import queries from './queries'; import mutations from './mutations'; export default new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: queries }), mutation: new GraphQLObjectType({ name: 'Mutation', fields: mutations }) });