Skip to content

GraphQL Resolvers

Resolvers are the functions responsible for fetching the data for a specific field in your schema. They tell GraphQL how to get the data for each query, mutation, or subscription.


What Is a Resolver?

  • Each field in your schema can have a resolver function.
  • Resolvers receive arguments and context, and return the data requested.
  • If you don’t provide a resolver, GraphQL uses a default resolver that returns the property of the same name on the parent object.

Resolver Function Signature

A resolver typically has this signature:

fieldName(parent, args, context, info) {
  // return data
}
Parameter Description
parent The result returned from the previous resolver (or root object)
args An object containing the arguments passed in the query
context Shared object accessible by all resolvers (e.g., auth info, DB)
info Info about the execution state, field name, schema, etc.

Example Resolver

Given this schema:

type Query {
  user(id: ID!): User
}

type User {
  id: ID!
  name: String!
}
Example resolver implementation
const resolvers = {
  Query: {
    user: (parent, args, context, info) => {
      const { id } = args;
      return context.db.getUserById(id);
    },
  },
};

Resolver for Nested Fields

Resolvers are called for every field requested.

type Post {
  id: ID!
  title: String!
  author: User!
}
Resolver example
const resolvers = {
  Post: {
    author: (post, args, context, info) => {
      return context.db.getUserById(post.authorId);
    },
  },
};

The post parameter contains the parent object with data resolved from the parent field.


Default Resolver Behavior

If no resolver is defined for a field, GraphQL uses a default resolver which:

  • Returns the property on the parent object with the same name as the field.
  • For example, if the parent object has { name: 'Alice' } and the query requests name, it returns 'Alice'.

Context Object

The context is useful for:

  • Authentication and authorization data
  • Database connections or data sources
  • Caching mechanisms
  • Per-request state
Example
const server = new ApolloServer({
  schema,
  context: ({ req }) => {
    const user = authenticate(req.headers.authorization);
    return { user, db };
  },
});

Best Practices

  • ✅ Keep resolvers simple and focused
  • ✅ Delegate data fetching to dedicated services or data layers
  • ✅ Avoid heavy computation inside resolvers
  • ✅ Use batching and caching (e.g., DataLoader) to optimize nested resolver calls
  • ✅ Handle errors gracefully and return meaningful messages

Tools & Libraries


Summary

  • Resolvers are the bridge between your schema and your data sources.
  • Every field can have its own resolver function.
  • They receive arguments and context and return the requested data.