0
0
GraphQLquery~5 mins

Info argument in GraphQL

Choose your learning style9 modes available
Introduction
The info argument helps you understand what data the client wants in a GraphQL request. It tells your server exactly which fields to fetch and return.
When you want to get only the requested fields from a database to save time and resources.
When building a GraphQL resolver that needs to know which fields the client asked for.
When optimizing queries to avoid fetching unnecessary data.
When you want to pass the requested fields to another function or service for processing.
Syntax
GraphQL
function resolver(parent, args, context, info) {
  // use info to get requested fields
}
The info argument is the fourth parameter in a resolver function.
It contains details about the GraphQL query, including the fields requested by the client.
Examples
Logs the name of the field being resolved.
GraphQL
const resolver = (parent, args, context, info) => {
  console.log(info.fieldName);
};
Extracts the list of fields the client requested in the query.
GraphQL
const requestedFields = info.fieldNodes[0].selectionSet.selections.map(field => field.name.value);
Sample Program
This example shows a GraphQL query for a user requesting only id and name. The resolver uses the info argument to return only those fields.
GraphQL
const { graphql, buildSchema } = require('graphql');

const schema = buildSchema(`
  type Query {
    user(id: ID!): User
  }
  type User {
    id: ID
    name: String
    email: String
  }
`);

const root = {
  user: (parent, args, context, info) => {
    // Simulated database record
    const userData = { id: '1', name: 'Alice', email: 'alice@example.com' };

    // Get requested fields
    const requestedFields = info.fieldNodes[0].selectionSet.selections.map(field => field.name.value);

    // Return only requested fields
    const result = {};
    requestedFields.forEach(field => {
      if (userData.hasOwnProperty(field)) {
        result[field] = userData[field];
      }
    });
    return result;
  }
};

const query = `{
  user(id: "1") {
    id
    name
  }
}`;

graphql(schema, query, root).then(response => {
  console.log(JSON.stringify(response.data, null, 2));
});
OutputSuccess
Important Notes
The info argument helps avoid fetching data you don't need, improving performance.
It can be complex to parse deeply nested queries, but libraries exist to help.
Always check if the requested field exists in your data before returning it.
Summary
The info argument tells your resolver which fields the client wants.
Use info to return only requested data and save resources.
It is the fourth parameter in every GraphQL resolver function.