0
0
GraphQLquery~30 mins

Context argument in GraphQL - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Context Argument in GraphQL Resolvers
📖 Scenario: You are building a simple GraphQL API for a bookstore. You want to use the context argument in your resolvers to access user information for authorization.
🎯 Goal: Create a GraphQL resolver that uses the context argument to check if a user is logged in before returning the list of books.
📋 What You'll Learn
Create a books array with three books, each having id and title.
Create a context object with a user property set to { name: 'Alice' }.
Write a resolver function called getBooks that takes parent, args, and context as arguments.
Inside getBooks, check if context.user exists; if yes, return the books array.
If context.user does not exist, return an empty array.
💡 Why This Matters
🌍 Real World
Using the context argument in GraphQL resolvers is essential for managing user authentication and authorization in real-world APIs.
💼 Career
Understanding how to access and use context in GraphQL is a key skill for backend developers working with modern API technologies.
Progress0 / 4 steps
1
Create the books data array
Create an array called books with these exact objects: { id: 1, title: '1984' }, { id: 2, title: 'Brave New World' }, and { id: 3, title: 'Fahrenheit 451' }.
GraphQL
Need a hint?

Use const books = [ ... ] to create the array with the exact book objects.

2
Create the context object with user info
Create a constant called context and set it to an object with a user property equal to { name: 'Alice' }.
GraphQL
Need a hint?

Use const context = { user: { name: 'Alice' } } to create the context object.

3
Write the getBooks resolver using context
Write a function called getBooks that takes parent, args, and context as parameters. Inside, check if context.user exists. If yes, return the books array.
GraphQL
Need a hint?

Define function getBooks(parent, args, context) and use if (context.user) to check user presence.

4
Complete getBooks to return empty array if no user
Add an else clause to getBooks that returns an empty array [] if context.user does not exist.
GraphQL
Need a hint?

Use else { return [] } to handle the case when no user is present.