[英]GraphQL query with multiple nested resolvers and mapping fields to arguments
From GraphQL Client's perspective, how do I perform a query with multiple nested resolvers where the fields from the parent are passed as arguments to the child resolver?从 GraphQL 客户端的角度来看,如何使用多个嵌套解析器执行查询,其中父字段作为 arguments 传递给子解析器?
Here is a minimal example:这是一个最小的例子:
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]!
}
Is it possible to write a query to get all authors and their last released book?是否可以编写查询以获取所有作者及其最后出版的书籍? Something around the lines:线条周围的东西:
query GetAuthorsWithLastBook($first: Int!) {
getAllAuthors(first: $first) {
authorId: id
name
lastBook: getBooksByAuthor(1, authorId) {
title
}
}
}
In the example above, I attempted to alias getAllAuthors.id
as authorId
and pass the alias down as argument to getBooksByAuthor(...)
but that didn't work.在上面的示例中,我尝试将getAllAuthors.id
别名为authorId
并将别名作为参数传递给getBooksByAuthor(...)
,但这不起作用。
The key aspect of the problem is that I don't know the authorId
s beforehand.问题的关键方面是我事先不知道authorId
。 I could fetch the authors first and build a query to fetch their last book but that will result in multiple queries and that is something I would like to avoid.我可以先获取作者并构建一个查询来获取他们的最后一本书,但这会导致多个查询,这是我想避免的。
A Java Kickstarter example is available here:https://www.graphql-java-kickstart.com/tools/schema-definition/此处提供 Java Kickstarter 示例:https://www.graphql-java-kickstart.com/tools/schema-definition/
yes, on the graphql definition, you need to add lastBook
in the Author是的,在 graphql 定义上,需要在 Author 中添加lastBook
type Author {
id: ID!
name: String!
lastBook: [Book]
}
Next up u need to write the resolver for the lastBook
接下来你需要为lastBook
编写解析器
const resolvers = {
Query: {
Author {
lastBook: (parent, args) {
const userId = parent.id;
return getBooksByAuthor(userId, 1);
},
}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.