首页 文章

GraphQL嵌套查询定义

提问于
浏览
4

我正在尝试为我的查询创建树状结构,以摆脱像我这样的查询

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表示graphql-js .

1 回答

  • 4

    Short answer:
    type应该是包含所有字段的 GraphQLObjectType

    type: new GraphQLObjectType({ name: 'patientQuery', fields: { find, findOne } })
    

    Details: 我最终使用以下代码进行了此查询:

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

相关问题