0
0
GraphQLquery~30 mins

Info argument in GraphQL - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Info Argument in GraphQL Resolvers
📖 Scenario: You are building a simple GraphQL server for a bookstore. You want to understand how to use the info argument in your resolver functions to access details about the GraphQL query being executed.
🎯 Goal: Learn how to use the info argument in a GraphQL resolver to inspect the query's field name and selection set.
📋 What You'll Learn
Create a resolver function for a book query
Use the info argument to get the field name being queried
Extract the selection set (requested fields) from the info argument
Return a simple object representing a book with the requested fields
💡 Why This Matters
🌍 Real World
GraphQL servers often use the 'info' argument in resolvers to understand what data the client requests, enabling efficient data fetching and response shaping.
💼 Career
Understanding the 'info' argument is essential for backend developers working with GraphQL APIs to optimize performance and customize responses.
Progress0 / 4 steps
1
Setup a basic book query resolver
Create a resolver function called book that takes four arguments: parent, args, context, and info. For now, return a hardcoded object with title set to '1984' and author set to 'George Orwell'.
GraphQL
Need a hint?

Remember the resolver function signature is (parent, args, context, info).

2
Add a variable to get the field name from info
Inside the book resolver, create a variable called fieldName and set it to info.fieldName. This will hold the name of the field being queried.
GraphQL
Need a hint?

The info argument contains metadata about the query, including fieldName.

3
Extract the selection set from info
Inside the book resolver, create a variable called selectionSet and set it to info.fieldNodes[0].selectionSet.selections. This will hold the list of fields requested by the client.
GraphQL
Need a hint?

The fieldNodes array contains AST nodes for the query fields. Access the first node's selectionSet to get requested fields.

4
Return only requested fields from the resolver
Modify the book resolver to return an object that includes only the fields requested in selectionSet. Create an object bookData with title as '1984' and author as 'George Orwell'. Then build a new object result by iterating over selectionSet and adding only those fields from bookData. Return result.
GraphQL
Need a hint?

Use a for loop to iterate over selectionSet and build the result object with only requested fields.