0
0
GraphQLquery~5 mins

Why resolvers connect schema to data in GraphQL

Choose your learning style9 modes available
Introduction

Resolvers act like helpers that fetch the actual data when you ask for something in GraphQL. They connect the shape of your data (schema) to where the data lives.

When you want to get user details from a database after asking for user info in GraphQL.
When you need to combine data from different sources like APIs and databases in one query.
When you want to control exactly how data is fetched or transformed before sending it back.
When you want to add custom logic like filtering or authorization before returning data.
Syntax
GraphQL
resolverName(parent, args, context, info) {
  // code to fetch or compute data
  return data;
}
Resolvers are functions that match fields in your GraphQL schema.
They receive arguments and return the data for that field.
Examples
This resolver fetches a user by ID from a database when the user field is requested.
GraphQL
const resolvers = {
  Query: {
    user(parent, args, context, info) {
      return database.getUserById(args.id);
    }
  }
};
This resolver combines first and last name fields into a full name.
GraphQL
const resolvers = {
  User: {
    fullName(parent) {
      return `${parent.firstName} ${parent.lastName}`;
    }
  }
};
Sample Program

This simple example shows a resolver for the 'hello' field that returns a greeting string.

GraphQL
const { graphql, buildSchema } = require('graphql');

const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

const root = {
  hello: () => 'Hello, world!'
};

graphql(schema, '{ hello }', root).then((response) => {
  console.log(response.data);
});
OutputSuccess
Important Notes

Every field in your schema can have a resolver function.

If you don't write a resolver, GraphQL tries to return a default value from the parent object.

Resolvers help keep your schema clean and your data fetching logic organized.

Summary

Resolvers connect schema fields to actual data sources.

They are functions that run when a field is requested.

Resolvers let you control how and where data is fetched or computed.