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.
function resolver(parent, args, context, info) { // use info to get requested fields }
const resolver = (parent, args, context, info) => { console.log(info.fieldName); };
const requestedFields = info.fieldNodes[0].selectionSet.selections.map(field => field.name.value);
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)); });
info argument in a GraphQL resolver?info providesinfo argument contains details about the query, including which fields the client requested.info argument in a GraphQL resolver function?info.fieldNodes[0].selectionSet.selections.map(f => f.name.value) return if the client queries { user { id name } }?id and name inside user.info.fieldNodes[0].selectionSet.selections lists the fields requested inside user, which are id and name.function resolver(parent, args, context) { return info.fieldNodes; }. Why does this cause an error?info.infoinfo is not declared, trying to use it causes a reference error.info argument in its parameters. -> Option Binfo argument is best?info to get requested fieldsinfo.fieldNodes provides the exact fields the client asked for, so you can fetch only those.info.fieldNodes to find requested fields and fetch only those from the database. uses info correctly. Options B, C, and D either waste resources or guess incorrectly.info.fieldNodes to find requested fields and fetch only those from the database. -> Option DPass the test and this pattern moves unknown