GraphQL没有加载子列表

时间:2017-11-05 22:10:10

标签: node.js graphql

我开始编写详细的GraphQL并切换到graphql-toolsmakeExecutableSchema,并根据更改加载user(id: "N")usersgroup(id: "N")的查询然而,groups和嵌套列表只返回"id": null。我觉得我必须在某个地方犯一个小错误,但我没有看到它:

const { makeExecutableSchema } = require('graphql-tools')

const db = require('./db')

const typeDefs = `
  type User {
    id: String
    first_name: String!
    last_name: String!
    email: String!
    friends: [User!]
    groups: [Group!]
  }

  type Group {
    id: String
    name: String!
  }

  type Query {
    users: [User!]!
    user(id: String!): User
    groups: [Group!]!
    group(id: String!): Group
  }
`

const resolvers = {
  Query: {
    users: db.readAllUsers,
    user: (root, args, { loaders }) => loaders.user.load(args.id),
    groups: db.readAllGroups,
    group: (root, args, { loaders }) => loaders.group.load(args.id)
  }
}

module.exports = makeExecutableSchema({ typeDefs, resolvers })

非常感谢任何帮助!

编辑:澄清,here's what the data source looks like

1 个答案:

答案 0 :(得分:1)

您已为查询定义了解析器,而您只是查询类型的字段。但是,group类型的User字段没有任何解析器,因此GraphQL会回退到使用该字段的默认解析器。由于对象User上的属性字段解析为只是一个id数组,因此GraphQL不知道如何理解它 - 毕竟,你告诉它组是一个对象数组。

您需要为groups字段添加解析器,并将该数组转换为将转换为Group个对象数组的Promise:

const resolvers = {
  Query: {
    users: db.readAllUsers,
    user: (root, args, { loaders }) => loaders.user.load(args.id),
    groups: db.readAllGroups,
    group: (root, args, { loaders }) => loaders.group.load(args.id)
  },
  User: {
    groups: ({ groups }, args, { loaders }) => {
      return Promise.all(groups.map(id => loaders.group.load(id)))
    }
  }
}