新 GraphQL buildSchema 的嵌套查询

Nested query for the new GraphQL buildSchema

如何使用新的 GraphQL 模式语言为我的 friendList 创建解析器? friendList 有一组人 _id。

我的新人使用 GraphQL Schema 语言打字:

const schema = buildSchema(`
  type People {
    _id: String
    firstName: String
    lastName: String
    demo: String
    friendList: [People]
  }
  type Query {
    getPeople(_id: String): People
  }
`);

我的老人用 GraphQLObjectType 打字:

const PeopleType = new GraphQLObjectType({
  name: 'People',
  fields: () => ({
    _id: {
      type: GraphQLString,
    },
    firstName: {
      type: GraphQLString,
    },
    lastName: {
      type: GraphQLString,
    },
    friendList: {
      type: new GraphQLList(PeopleType),
      // pass @friends parentValue
      resolve: ({ friends }) {
        return People.find({ _id: { $in: friends } }).then(res => res);
    },
  }),
});

我想实现这个查询:

{
  people(_id: "ABC123") {
    firstName
    lastName
    friendList {
      firstName
      lastName
    }
  }

我找不到使用 graphql-js 执行此操作的方法,因此我转而使用 Apollo 人员提供的类似实现,称为 graphql-tools。

http://dev.apollodata.com/tools/graphql-tools/generate-schema.html

他们有一个名为 makeExecutableSchema 的函数,它采用用 GraphQL 模式语言编写的模式并将其与(嵌套的)解析器函数结合起来。这解决了这个问题,如果您的代码使用 GraphQL Schema 语言,那么集成起来实际上非常简单。

他们还有另一个不可知的工具来公开这个取代 express-graphql 的新模式,它的 GraphQL 服务器:

http://dev.apollodata.com/tools/graphql-server/index.html

查看文档,希望这能让您灵活地使用 GraphQL Schema 语言语法编写复杂代码!

您的解析器应该 return 一个 class 的新实例,如更新的 GraphQL 文档中所述:http://graphql.org/graphql-js/object-types/.

class People {
  friendList () {}
}
var rootValue = {
  getPeople: function () {
    return new People();
  }
}