【问题标题】:GraphQL query with multiple nested resolvers and mapping fields to arguments具有多个嵌套解析器并将字段映射到参数的 GraphQL 查询
【发布时间】:2021-05-19 23:42:07
【问题描述】:

从 GraphQL 客户端的角度来看,如何使用多个嵌套解析器执行查询,其中父字段作为参数传递给子解析器?

这是一个最小的例子:

GraphQL 架构:

type Author {
  id: ID!
  name: String!
}

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


type Query {
  // Returns a list of Authors ordered by name, 'first' indicates how many entries to return
  getAllAuthors(first: Int!): [Author]!
  // Returns a list of Books ordered by releaseDate, 'first' indicates how many entries to return
  getBooksByAuthorId(first: Int! authorId: ID!): [Book]!
}

是否可以编写查询来获取所有作者及其最近出版的书籍?线条周围的东西:

query GetAuthorsWithLastBook($first: Int!) {
  getAllAuthors(first: $first) {
    authorId: id
    name
    lastBook: getBooksByAuthor(1, authorId) {
      title
    }
  }
}

在上面的示例中,我尝试将 getAllAuthors.id 别名为 authorId 并将别名作为参数传递给 getBooksByAuthor(...),但这没有用。

问题的关键在于我事先不知道authorIds。我可以先获取作者并构建一个查询来获取他们的最后一本书,但这会导致多个查询,这是我想避免的。

更新

此处提供了 Java Kickstarter 示例:https://www.graphql-java-kickstart.com/tools/schema-definition/

【问题讨论】:

    标签: graphql


    【解决方案1】:

    是的,在graphql定义上,需要在Author中添加lastBook

    type Author {
      id: ID!
      name: String!
      lastBook: [Book]
    }
    

    接下来你需要为lastBook编写解析器

    const resolvers = {
      Query: {
        Author {
          lastBook: (parent, args) {
            const userId = parent.id;
            return getBooksByAuthor(userId, 1);
          },
        }
      }
    };
    

    【讨论】:

    猜你喜欢
    • 2019-10-14
    • 2021-07-28
    • 2019-09-01
    • 2021-06-16
    • 1970-01-01
    • 2021-07-20
    • 2021-01-14
    • 2014-08-04
    • 1970-01-01
    相关资源
    最近更新 更多