We are going to explain what a resolver is in GraphQL, its role, how it maps fields to data sources, and then provide an example for a user(id: ID!) query.
Definition:
In GraphQL, a resolver is a function that is responsible for fetching the data for a specific field in the GraphQL schema. Each field in the schema can have a resolver function that determines how the data for that field is retrieved. Resolvers are the bridge between the GraphQL schema and the underlying data sources (like databases, REST APIs, etc.).
Role of a resolver:
- Data Fetching: The primary role of a resolver is to return the value for a field in the GraphQL query. This value can come from a database, an API, a cache, or even be computed.
- Linking Schema to Data Sources: Resolvers map the abstract GraphQL schema to concrete data retrieval logic. They tell the GraphQL server how to get the data for each field.
- Handling Arguments: Resolvers receive the arguments provided in the query (like
id in user(id: ID!)) and use them to fetch the specific data.
- Parent-Child Relationship: In nested queries, resolvers can access the parent object's resolved value (via the
parent or root argument) to fetch nested data. This allows for efficient data loading and relationships.
- Async Operations: Since data fetching is often asynchronous (like database calls), resolvers can return promises.
How a resolver maps a field to a backend data source:
- Each field in the GraphQL schema can have an associated resolver. If a field does not have an explicit resolver, the default resolver will try to get the value by looking for a property with the same name on the parent object.
- The resolver function typically receives four arguments:
parent (or root): The result of the parent resolver (for top-level fields, this is often the rootValue passed to the server or the query itself).
args: The arguments provided to the field in the query (like { id: "123" }).
context: An object shared by all resolvers in a request, often used for authentication, database connections, etc.
info: Contains information about the query, including the field being resolved and the query structure.
- The resolver uses these arguments to fetch the relevant data and returns it.
Example for a user(id: ID!) query:
Let's assume we have a GraphQL schema:
type Query {
user(id: ID!): User
}
type User {
id: ID!
name: String
email: String
}
We are going to write a resolver for the user field in the Query type.
We assume we have a data source, say a User model or a function that can fetch a user by id from a database.
In JavaScript (using a common GraphQL server library like Apollo Server or express-graphql):
// Assuming we have a User model with a static findById method
const resolvers = {
Query: {
user: (parent, args, context, info) => {
const { id } = args;
// We use the id to fetch the user from the database
return User.findById(id);
// Alternatively, if using a REST API or other source, we might do:
// return fetch(`/users/${id}`).then(res => res.json());
}
},
// We might also have resolvers for the User type fields, but note that by default,
// if the User object returned from the query resolver has `id`, `name`, and `email` properties,
// then the default resolvers will work. However, we can override them.
User: {
// For example, if we want to compute the email field differently, we could write:
// email: (parent) => parent.email.toLowerCase(),
// But if the user object already has the email, we don't need to define it.
}
};
Explanation of the example:
- The
user resolver is for the Query.user field. It takes the args (which includes id), and then uses that id to fetch the user from the database via User.findById(id).
- The
User type fields (like id, name, email) by default use the default resolver which simply returns the corresponding property from the parent object (the user object we fetched). So if the user object has these properties, we don't need to write resolvers for them.
- However, if we had a field that required a different data source or computation, we would write a resolver for that field in the
User type.
Important note: In a real application, we might handle errors and edge cases (like user not found) in the resolver. Also, we might use the context to get a database connection or a service instance.
Let's adjust the example to handle a not found scenario and use context:
const resolvers = {
Query: {
user: async (parent, args, context, info) => {
const { id } = args;
try {
const user = await context.userService.getUserById(id);
if (!user) {
throw new Error('User not found');
}
return user;
} catch (error) {
// Handle the error appropriately, maybe log and re-throw or return a specific error object.
throw error;
}
}
}
};
In this adjusted example, we are using context.userService to get the user. The context is set up when the GraphQL server is created and can contain database connections, authentication information, etc.
This conceptual example should give a clear idea of what a resolver is and how it works.
What is a Resolver in GraphQL?
A resolver is a function that determines how GraphQL fields fetch their data. It's the bridge between your GraphQL schema (what clients can query) and your backend data sources (databases, APIs, caches, etc.).
Core Responsibilities:
- Field Resolution - Returns the value for a specific field in a query
- Argument Handling - Processes arguments passed in queries (e.g.,
user(id: "123"))
- Data Fetching - Retrieves data from databases, microservices, or other sources
- Parent-Child Linking - Accesses parent object values for nested queries
- Error Handling - Manages errors during data fetching
How Resolvers Map Schema Fields to Data Sources
Resolver Structure (4 Parameters):
fieldResolver: (parent, args, context, info) => {
// 1. parent: Result from parent resolver (or root for top-level)
// 2. args: Query arguments ({ id: "123" })
// 3. context: Shared request-scoped object (auth, DB connections)
// 4. info: Query AST, field name, return type metadata
}
Mapping Process:
- Schema Definition → Declares what data is available
- Resolver Attachment → Connects each field to fetching logic
- Execution Flow → GraphQL engine calls resolvers in query order
- Data Assembly → Resolved values compose the final response
Example: user(id: ID!) Query Resolver
1. GraphQL Schema:
type Query {
user(id: ID!): User
}
type User {
id: ID!
name: String
email: String
}
2. Resolver Implementation:
// Resolver map for Query type
const resolvers = {
Query: {
// Resolver for 'user' field in Query type
user: async (parent, args, context, info) => {
const { id } = args;
// Access database connection from context
const db = context.db;
try {
// Fetch user from database
const user = await db.users.findOne({ where: { id } });
if (!user) {
// Optional: Return null for non-existent users (or throw error)
return null;
}
// Return user object (matches User type fields)
return user;
} catch (error) {
// Log error, possibly throw GraphQLError
console.error(`Failed to fetch user ${id}:`, error);
throw new Error(`User ${id} not found`);
}
}
},
// Optional: Custom resolvers for User fields (if needed)
User: {
// Example: Computed field or different data source
email: (parent) => parent.email.toLowerCase(),
// Example: Another database call for nested field
// posts: (parent, args, context) =>
// context.db.posts.find({ userId: parent.id })
}
};
3. Complete Request Flow:
Query:
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
Variables: { "id": "123" }
Execution:
- GraphQL engine calls
Query.user resolver with args = { id: "123" }
- Resolver fetches user from database →
{ id: "123", name: "Alice", email: "ALICE@EXAMPLE.COM" }
- For nested
User fields, default resolver accesses object properties
- Response:
{
"data": {
"user": {
"id": "123",
"name": "Alice",
"email": "alice@example.com" // (if custom resolver lowercased it)
}
}
}
Key Concepts Illustrated:
1. Field-to-Resolver Mapping:
Schema Field → Resolver Function
Query.user → Query.user resolver
User.name → (Default: parent.name) or User.name resolver
User.email → User.email resolver (if defined)
2. Data Source Abstraction:
// Resolver hides data source complexity
user: (parent, { id }) => {
// Could be:
// 1. SQL: await db.query('SELECT * FROM users WHERE id = ?', [id])
// 2. MongoDB: await User.findById(id)
// 3. REST: await fetch(`/api/users/${id}`)
// 4. Cache: await redis.get(`user:${id}`)
// 5. Combination: Check cache first, then DB
}
3. Context Usage Pattern:
// Server setup with context
const server = new ApolloServer({
typeDefs,
resolvers,
context: async ({ req }) => {
// Shared across all resolvers in request
return {
db: getDatabaseConnection(),
currentUser: authenticate(req),
services: {
userService: new UserService(),
emailService: new EmailService()
}
};
}
});
// Resolver accesses context
user: (parent, args, context) => {
return context.services.userService.findById(args.id);
}
Common Resolver Patterns:
A. Batch Loading (N+1 Problem Solution):
// Use DataLoader (Facebook's batching utility)
const resolvers = {
User: {
posts: (parent, args, context) => {
// DataLoader batches requests for same parent type
return context.loaders.postsByUserId.load(parent.id);
}
}
};
B. Permission Checks:
user: (parent, { id }, context) => {
// Check if user can access this resource
if (!context.currentUser || context.currentUser.id !== id) {
throw new ForbiddenError('Not authorized');
}
return context.db.users.find(id);
}
C. Microservice Composition:
user: async (parent, { id }, context) => {
// Fetch from multiple services
const [profile, orders] = await Promise.all([
context.services.profileService.getProfile(id),
context.services.orderService.getUserOrders(id)
]);
return { ...profile, orders };
}
Important Notes:
-
Root Resolvers vs. Field Resolvers:
- Root fields (in
Query/Mutation) get parent = {} (or rootValue)
- Nested fields get
parent = result from parent resolver
-
Default Resolver: If no resolver is defined, GraphQL returns parent[fieldName] (object property)
-
Async Resolvers: Always return Promises/Async results for DB calls
-
Performance: Resolvers execute top-down, left-to right - optimize with batching/caching
-
Error Propagation: Thrown errors bubble up unless caught
When You Need Custom Resolvers:
- Fetching from database/external API
- Formatting/transforming data
- Implementing business logic
- Joining multiple data sources
- Handling authentication/authorization
- Adding computed fields
- Solving N+1 problems with DataLoader
The resolver pattern gives GraphQL its flexibility - you can mix REST APIs, SQL/NoSQL databases, and microservices under a unified schema without changing the client's query structure.