【问题标题】:Apollo GraphQL server: In resolvers, get variables from several levels higherApollo GraphQL 服务器:在解析器中,从更高级别获取变量
【发布时间】:2017-12-07 09:13:16
【问题描述】:

在我的解析器中说我有以下内容:

Query: {
  author: (root, args) => API.getAuthor(args.authorId),
},
Author: {
  book: (author, args) => API.getBook(author.id, args.bookId),
},
Book: {
  // Here, I can't get the author ID
  chapter: (book, args) => API.getChapter(authorId???, book.id, args.chapterId),
}

从上面的例子中我的问题很清楚,我怎样才能从更高的几个级别访问变量? 我希望能够提出如下请求:

author(authorId: 1) {
  id
  book(bookId: 31) {
    id
    chapter(chapterId: 3) {
      content
    }
  }
}

而我获取特定章节的连接器也需要作者的ID。

【问题讨论】:

  • 你不能,这是故意的
  • 这本书没有'author_id'字段吗?
  • @whitep4nther 哦该死的,为什么?不,在我的真实案例中,book 没有 author_id 字段。
  • 那是因为Book实体也可以包含在其他对象中。您现在拥有author { book { chapter } },但您也可以拥有library { book { chapter } }。每个对象都负责用自己的数据获取他的字段,这使得整个事情可以组合。不过我有一个解决方案的想法,所以我正在写一个答案。

标签: graphql relayjs graphql-js apollo react-apollo


【解决方案1】:

您无法在 GraphQL 中访问更高级别的变量。

这是有意的:因为Book 实体也可以包含在其他对象中。现在,您拥有author { book { chapter } },但您也可以拥有library { book { chapter } },其中author 字段不会出现在查询中,从而使author.id 变量无法访问。

每个对象都负责用自己的数据获取他的字段,这使得整个事情可以组合。

不过,您可以做的是扩展 API.getBooks 函数的响应,将 author_id 字段添加到返回的对象中。这样,您就可以在 Book 实体中访问它:book.authorId

function myGetBook(authorId, bookId) {
  return API.getBook(authorId, bookId)
    .then(book => {
      return Object.assign(
        {},
        theBook,
        { authorId }
      );
    });
}

然后:

Author: {
  book: (author, args) => myGetBook(author.id, args.bookId),
},
Book: {
  chapter: (book, args) => API.getChapter(book.authorId, book.id, args.chapterId),
}

【讨论】:

    猜你喜欢
    • 2020-09-11
    • 2021-08-22
    • 2019-07-15
    • 2021-05-02
    • 2017-04-15
    • 2020-09-11
    • 2018-01-05
    • 2020-03-27
    • 2020-08-12
    相关资源
    最近更新 更多