How to Create Resolver in GraphQL: Simple Guide
In GraphQL, a
resolver is a function that fetches the data for a specific field in your schema. You create a resolver by defining a function that matches the field name inside a resolver map object, which the GraphQL server uses to return the requested data.Syntax
A resolver is a function inside an object that matches your GraphQL schema fields. It receives parameters like parent, args, context, and info. The basic syntax looks like this:
parent: The result from the previous resolver (or root for top-level).args: Arguments passed to the field in the query.context: Shared data like authentication info.info: Info about the execution state.
javascript
const resolvers = { Query: { fieldName: (parent, args, context, info) => { // return data for fieldName } } };
Example
This example shows a simple GraphQL resolver that returns a greeting message. The hello field in the Query type is resolved by a function that returns a string.
javascript
const { ApolloServer, gql } = require('apollo-server'); // Define schema const typeDefs = gql` type Query { hello: String } `; // Define resolvers const resolvers = { Query: { hello: () => 'Hello, world!' } }; // Create server const server = new ApolloServer({ typeDefs, resolvers }); // Start server server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
Output
Server ready at http://localhost:4000/
Common Pitfalls
Common mistakes when creating resolvers include:
- Not matching resolver names exactly with schema fields.
- Forgetting to return data from the resolver function.
- Ignoring the
argsparameter when the field expects arguments. - Not handling asynchronous data fetching properly (use
asyncandawait).
javascript
const resolvers = { Query: { // Wrong: missing return hello: () => { return 'Hello, world!'; }, // Right: greet: () => { return 'Hello, world!'; } } };
Quick Reference
| Term | Description |
|---|---|
| Resolver | Function that returns data for a schema field |
| parent | Result from previous resolver or root object |
| args | Arguments passed in the query for the field |
| context | Shared info like auth or database connection |
| info | Execution state info, rarely used directly |
Key Takeaways
Create resolvers as functions matching schema field names inside a resolver map.
Always return data from your resolver functions, using async if needed.
Use the args parameter to access query arguments in resolvers.
Match resolver structure exactly to your GraphQL schema for correct data fetching.
Use context to share data like authentication or database connections across resolvers.