Nested Resolvers and Parent Values
GraphQL fields can contain nested objects, and nested fields can have their own resolvers.
Consider:
type User {
id: ID!
name: String!
posts: [Post!]!
}
type Post {
id: ID!
title: String!
}
A query may request:
query {
user(id: "42") {
id
name
posts {
id
title
}
}
}
The Query.user resolver can return a user object. The User.posts resolver can then use that returned object as its parent value.
const resolvers = {
Query: {
user: (_, { id }, context) => context.userService.findById(id)
},
User: {
posts: (user, _, context) => {
return context.postService.findByUserId(user.id);
}
}
};
This is one of the most important concepts in GraphQL execution.
The parent resolver does not necessarily have to fetch every nested relation immediately. Each nested field can resolve its own data.
This flexibility can become a performance problem if implemented naively. If a query requests 100 users and each user's posts resolver performs a separate database query, the server can encounter the classic N+1 query problem. DataLoader and batching techniques will be covered later in the course.
- Nested fields can have their own resolvers.
- The parent argument contains the value returned by the parent field.
- Nested resolvers enable flexible data composition.
- Naive nested resolution can produce N+1 database queries.
In a `User.posts` resolver, what does the `parent` argument commonly contain?