新GraphQL buildSchema的嵌套查询

Abu*_*der 8 graphql graphql-js

如何使用新的GraphQL Schema语言为我的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
  }
`);
Run Code Online (Sandbox Code Playgroud)

我的老人用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);
    },
  }),
});
Run Code Online (Sandbox Code Playgroud)

我想实现这个查询:

{
  people(_id: "ABC123") {
    firstName
    lastName
    friendList {
      firstName
      lastName
    }
  }
Run Code Online (Sandbox Code Playgroud)

xpe*_*int 9

您的解析器应返回类的新实例,如更新的GraphQL文档中所述:http://graphql.org/graphql-js/object-types/ .

class People {
  friendList () {}
}
var rootValue = {
  getPeople: function () {
    return new People();
  }
}
Run Code Online (Sandbox Code Playgroud)


Cha*_*ess 4

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

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

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

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

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

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