Apollo Server 中的嵌套查询

Nested queries in Apollo Server

我正在使用 apollo-server 构建 GraphQL 模式。我的模式有大量查询,我想将它们组合在一起。有没有办法按域对它们进行分组,以便我可以进行如下查询:

query {
  Books {
    getAll {
      ...
    }
    getByUser {
      ...
    }
  }
}

我可以用 graphql-dotnet 做到这一点,但我不确定如何用 apollo-server 做到这一点。

给定这样的模式

type Query {
  books: Books
}

type Books {
  getAll: [Book!]!
}

type Book {
  id: ID!
  title: String!
}

您的解析器需要类似于:

const resolvers = {
  Query: {
    books: () => {
      return {}
    },
  },
  Books: {
    getAll: () => {
      # return list of books
    }
  }
}

books 字段 return 是一个对象类型 (Books),因此解析器 必须 return 一个对象,即使它是如上所示的空对象。如果该字段解析为空,则其子字段的 none 将被解析,即使它们被请求也是如此。通过 returning 一个空对象,我们确保子字段也将被解析。