What is Resolver Chain in GraphQL: Explanation and Example
resolver chain is the sequence of resolver functions called to fetch data for nested fields in a query. Each resolver handles its part and passes results to the next, enabling complex data fetching in a structured way.How It Works
Imagine ordering a meal at a restaurant where each course is prepared by a different chef. The waiter takes your order and passes it along to the appetizer chef, then the main course chef, and finally the dessert chef. In GraphQL, the resolver chain works similarly: each field in a query has a resolver function that fetches or computes the data for that field. When a query asks for nested data, GraphQL calls resolvers one after another, passing the results down the chain.
This chain starts at the root resolver for the query type. For each field requested, GraphQL calls its resolver, which can return a value or another object. If the field has subfields, GraphQL continues calling resolvers for those subfields, creating a chain of resolver calls. This allows GraphQL to efficiently gather all requested data in a single query.
Example
This example shows a simple resolver chain where a query asks for a user and their posts. Each resolver returns data that the next resolver uses to fetch nested information.
const { graphql, buildSchema } = require('graphql'); // Define schema with nested fields const schema = buildSchema(` type Query { user(id: ID!): User } type User { id: ID name: String posts: [Post] } type Post { id: ID title: String } `); // Sample data const users = [{ id: '1', name: 'Alice' }]; const posts = [{ id: 'a', title: 'Hello World', userId: '1' }]; // Resolvers const root = { user: ({ id }) => users.find(u => u.id === id), User: { posts: (user) => posts.filter(p => p.userId === user.id) } }; // Query requesting nested data const query = `{ user(id: "1") { name posts { title } } }`; // Execute query graphql(schema, query, root).then(response => { console.log(JSON.stringify(response.data, null, 2)); });
When to Use
Use a resolver chain whenever your GraphQL queries request nested or related data. This is common in real-world apps where you want to fetch an object and its related objects in one request, like a user and their posts or comments.
Resolver chains help keep your code organized by separating how each piece of data is fetched. They also improve efficiency by letting GraphQL call only the resolvers needed for the requested fields, avoiding over-fetching.
Key Points
- A resolver chain is the sequence of resolver functions called for nested GraphQL fields.
- Each resolver fetches or computes data for its field and passes results to the next.
- This chain enables efficient, structured data fetching in one query.
- Resolver chains keep code modular and improve query performance.