0
0
GraphQLquery~30 mins

Field-level permissions in GraphQL - Mini Project: Build & Apply

Choose your learning style9 modes available
Field-level Permissions in GraphQL
📖 Scenario: You are building a GraphQL API for a company that wants to control which users can see certain fields in the data. For example, only admins can see the salary field of employees, while all users can see the name and position fields.
🎯 Goal: Create a GraphQL schema with an Employee type that has fields name, position, and salary. Implement field-level permissions so that the salary field is only accessible to users with the role ADMIN.
📋 What You'll Learn
Define an Employee type with fields name, position, and salary
Create a query employees that returns a list of Employee
Add a context variable userRole to simulate the current user's role
Implement resolver logic to restrict access to the salary field based on userRole
Ensure users without ADMIN role receive null for the salary field
💡 Why This Matters
🌍 Real World
Field-level permissions are essential in real-world APIs to protect sensitive data and comply with privacy rules.
💼 Career
Understanding how to implement field-level permissions in GraphQL is valuable for backend developers building secure APIs.
Progress0 / 4 steps
1
Define the Employee type and Query
Create a GraphQL schema with an Employee type that has fields name (String), position (String), and salary (Float). Also define a Query type with a field employees that returns a list of Employee.
GraphQL
Hint

Use GraphQL SDL syntax to define types and fields exactly as specified.

2
Add userRole to context and sample data
Add a variable called userRole in the context to simulate the current user's role. Also create a sample list of employees with exact entries: { name: "Alice", position: "Developer", salary: 70000 } and { name: "Bob", position: "Manager", salary: 90000 }.
GraphQL
Hint

Define userRole as a string and employees as an array of objects with exact properties and values.

3
Implement resolver for employees query
Write a resolver function for the employees query that returns the employees list. Use the userRole variable from context to control access to the salary field by returning null for salary if userRole is not ADMIN. Use a field resolver for salary inside the Employee type.
GraphQL
Hint

Use a resolver for salary that checks userRole and returns null if not ADMIN.

4
Complete schema and export
Add the final code to create the GraphQL schema using makeExecutableSchema from @graphql-tools/schema with the defined typeDefs and resolvers. Export the schema as schema.
GraphQL
Hint

Use makeExecutableSchema with typeDefs and resolvers and export the schema.