0
0
GraphQLquery~30 mins

Sorting arguments in GraphQL - Mini Project: Build & Apply

Choose your learning style9 modes available
Sorting Arguments in GraphQL Queries
📖 Scenario: You are building a simple GraphQL API for a bookstore. The bookstore wants to allow users to query the list of books and sort them by different fields such as title or price.
🎯 Goal: Create a GraphQL query that accepts a sortBy argument to sort the list of books by the specified field.
📋 What You'll Learn
Define a GraphQL type Book with fields id, title, and price.
Create a query books that accepts a sortBy argument of type String.
Implement sorting logic in the resolver to return books sorted by the sortBy argument.
Support sorting by title and price only.
💡 Why This Matters
🌍 Real World
Sorting query results is a common feature in APIs to help users find data in the order they want, such as sorting products by price or name.
💼 Career
Understanding how to add arguments and sorting logic in GraphQL queries is essential for backend developers building flexible and user-friendly APIs.
Progress0 / 4 steps
1
Define the Book type and sample data
Create a GraphQL type called Book with fields id (ID!), title (String!), and price (Float!). Also, create a sample list of books called booksData with exactly these entries: { id: "1", title: "The Hobbit", price: 10.99 }, { id: "2", title: "1984", price: 8.99 }, and { id: "3", title: "Brave New World", price: 9.99 }.
GraphQL
Hint

Use type Book { ... } to define the type and create a constant array booksData with the given objects.

2
Add the sortBy argument to the books query
Add a query called books that returns a list of Book items. Add a sortBy argument of type String to this query.
GraphQL
Hint

Define a Query type with a books field that takes sortBy: String and returns a list of Book.

3
Implement resolver with sorting logic
Write a resolver function for books that accepts the sortBy argument. Sort the booksData array by title if sortBy is "title", or by price if sortBy is "price". Return the sorted array. If sortBy is not provided or invalid, return the original array unsorted.
GraphQL
Hint

Use args.sortBy to check the sorting field and return a new sorted array using Array.sort(). Use localeCompare for string sorting.

4
Complete the schema and export
Add the final code to create the executable 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 result as schema.