0
0
GraphQLquery~5 mins

Resolver organization in GraphQL

Choose your learning style9 modes available
Introduction

Resolvers tell GraphQL how to get the data for each part of a query. Organizing them well keeps your code clean and easy to understand.

When you have many fields in your GraphQL schema and want to keep code tidy.
When different parts of your data come from different sources like databases or APIs.
When you want to reuse resolver logic across multiple queries or mutations.
When working in a team and want everyone to find resolver code easily.
When you want to separate concerns and make testing easier.
Syntax
GraphQL
const resolvers = {
  Query: {
    fieldName: (parent, args, context, info) => {
      // return data
    }
  },
  Mutation: {
    mutationName: (parent, args, context, info) => {
      // perform action and return result
    }
  },
  TypeName: {
    fieldName: (parent, args, context, info) => {
      // resolve nested field
    }
  }
};

Resolvers are grouped by operation type: Query, Mutation, and custom types.

Each resolver is a function that returns the data for its field.

Examples
A simple resolver for a Query field named hello that returns a string.
GraphQL
const resolvers = {
  Query: {
    hello: () => 'Hello world!'
  }
};
A Mutation resolver that adds a user and returns the new user object.
GraphQL
const resolvers = {
  Mutation: {
    addUser: (parent, args) => {
      // add user logic
      return { id: 1, name: args.name };
    }
  }
};
A field resolver for a User type that combines first and last name.
GraphQL
const resolvers = {
  User: {
    fullName: (parent) => `${parent.firstName} ${parent.lastName}`
  }
};
Sample Program

This example sets up a simple GraphQL server with one Query field greeting. The resolver returns a greeting string.

GraphQL
const { ApolloServer, gql } = require('apollo-server');

const typeDefs = gql`
  type Query {
    greeting: String
  }
`;

const resolvers = {
  Query: {
    greeting: () => 'Hello from resolver!'
  }
};

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
OutputSuccess
Important Notes

Keep resolvers small and focused on one task.

Use separate files or folders to organize resolvers for large projects.

Resolvers receive four arguments: parent, args, context, and info.

Summary

Resolvers connect schema fields to data sources.

Organize resolvers by Query, Mutation, and type for clarity.

Good organization helps maintain and scale your GraphQL server.