What is Resolver in GraphQL: Definition and Usage
resolver is a function that fetches the data for a specific field in a query. It tells the server how to get the requested information, acting like a bridge between the query and the data source.How It Works
Think of a GraphQL query as a request for information, like ordering a meal at a restaurant. The resolver is like the chef who prepares each dish based on the order. Each field in the query has its own resolver that knows how to get or calculate the data needed.
When a client sends a query, GraphQL calls the resolver functions for each field in the query. These resolvers can fetch data from databases, APIs, or even compute values on the fly. The results from all resolvers are combined to form the final response sent back to the client.
Example
This example shows a simple GraphQL resolver that returns a user's name when queried.
const { ApolloServer, gql } = require('apollo-server'); // Define schema const typeDefs = gql` type Query { user: User } type User { id: ID name: String } `; // Sample data const userData = { id: '1', name: 'Alice' }; // Define resolvers const resolvers = { Query: { user: () => userData }, User: { name: (parent) => parent.name } }; // Create server const server = new ApolloServer({ typeDefs, resolvers }); // Start server server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
When to Use
Resolvers are used whenever you want to define how GraphQL should get the data for each field in your schema. Use resolvers to connect your GraphQL API to databases, REST APIs, or any other data sources.
For example, if you build a social media app, resolvers fetch user profiles, posts, comments, and likes from your database. They let you control exactly what data is returned and how it is combined, making your API flexible and efficient.
Key Points
- A resolver is a function that provides data for a GraphQL field.
- Each field in a query can have its own resolver.
- Resolvers can fetch data from any source or compute values.
- They are essential for connecting GraphQL queries to real data.