How to Write Resolver for Nested Type in GraphQL
To write a resolver for a nested type in GraphQL, define a resolver function for the parent type field that returns the nested object or array. Use
parent argument in the resolver to access the parent data and resolve the nested fields accordingly.Syntax
A resolver for a nested type is a function inside the parent type's resolver map. It receives parent, args, context, and info. The parent holds the parent object, letting you access nested data.
Example syntax:
ParentType: {
nestedField(parent, args, context, info) {
// return nested data based on parent
}
}javascript
const resolvers = { ParentType: { nestedField(parent, args, context, info) { // Access nested data from parent return parent.nestedField; } } };
Example
This example shows a User type with a nested posts field. The posts resolver uses the parent user object to return the user's posts.
javascript
const users = [ { id: 1, name: 'Alice', posts: [{ id: 101, title: 'Hello World' }, { id: 102, title: 'GraphQL Rocks' }] }, { id: 2, name: 'Bob', posts: [{ id: 103, title: 'Hi there' }] } ]; const resolvers = { Query: { user(parent, args) { return users.find(u => u.id === args.id); } }, User: { posts(parent) { return parent.posts; } } }; // Query example: // { // user(id: 1) { // name // posts { // title // } // } // }
Output
{
"data": {
"user": {
"name": "Alice",
"posts": [
{ "title": "Hello World" },
{ "title": "GraphQL Rocks" }
]
}
}
}
Common Pitfalls
- Not using the
parentargument to access nested data causes undefined results. - Returning the wrong data type (e.g., a single object instead of an array) for nested lists.
- Forgetting to define a resolver for nested fields when the default resolver cannot find the data.
javascript
const resolversWrong = { User: { posts() { // Missing parent argument, so no access to user's posts return null; // Wrong } } }; const resolversRight = { User: { posts(parent) { return parent.posts; // Correct } } };
Quick Reference
| Concept | Description |
|---|---|
| parent | The object returned by the parent resolver, used to access nested data. |
| args | Arguments passed to the field, used for filtering or parameters. |
| resolver function | A function that returns data for a specific field. |
| nested resolver | Resolver defined inside a parent type to resolve nested fields. |
| return value | Must match the GraphQL schema type for the field. |
Key Takeaways
Use the parent argument in nested resolvers to access the parent object's data.
Define a resolver for nested fields when default resolution is insufficient.
Return data matching the nested field's schema type (object or list).
Avoid missing the parent argument to prevent undefined nested data.
Test nested queries to ensure resolvers return expected results.