What is Parent Argument in Resolver in GraphQL
parent argument in a resolver is the result returned from the previous resolver in the resolver chain. It provides context or data from the parent field, allowing nested resolvers to access related information easily.How It Works
Imagine you are reading a family tree. Each person (field) can have children (nested fields). When you ask for a child's details, you first need to know about the parent. In GraphQL, the parent argument acts like this parent information passed down to child resolvers.
When a GraphQL query runs, it starts from the root resolver and moves down the fields. Each resolver can return data that becomes the parent argument for its child resolvers. This way, child resolvers can use the parent's data to fetch or compute their own results.
Example
This example shows a simple GraphQL schema with a user field and a nested posts field. The posts resolver uses the parent argument to get the user's ID and return only posts for that user.
const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]; const posts = [ { id: 1, userId: 1, title: 'Hello World' }, { id: 2, userId: 2, title: 'GraphQL Rocks' }, { id: 3, userId: 1, title: 'Resolvers Explained' } ]; const resolvers = { Query: { user: (_, args) => users.find(u => u.id === args.id) }, User: { posts: (parent) => posts.filter(post => post.userId === parent.id) } }; // Simulated query: { user(id: 1) { name posts { title } } } const user = resolvers.Query.user(null, { id: 1 }); const userPosts = resolvers.User.posts(user); console.log({ name: user.name, posts: userPosts.map(p => p.title) });
When to Use
Use the parent argument whenever you have nested fields in your GraphQL schema. It helps child resolvers access data from their parent field without extra queries.
For example, if you query a user and want their posts, the posts resolver uses the user data passed as parent to find posts belonging to that user. This keeps your code clean and efficient.
It is especially useful when your data is related, like orders belonging to a customer or comments belonging to a post.
Key Points
- The
parentargument holds the result from the previous resolver. - It allows nested resolvers to access data from their parent field.
- Helps avoid redundant data fetching by passing context down the resolver chain.
- Commonly used in nested queries to relate data efficiently.