Catalog Sorting and Analytics
Introduction: Enhancing the Book Catalog
Welcome back! In the previous lessons, you learned how to build the foundation of a book catalog and track user reading progress. Now, we will take your API to the next level by adding advanced sorting and analytics features. These improvements will help users find books more easily and allow you to provide valuable insights about each book in your catalog.
Sorting lets users organize the catalog in ways that are most useful to them, such as by title, author, or how much progress readers have made. Analytics gives you a deeper look at how books are being read, such as the average progress of all readers or the completion rate for a book. These features are common in real-world applications and make your API much more powerful and user-friendly.
Expose avgProgress in the catalog query DTO
Here we allow clients to request sorting by average progress across readers.
What changed
- Added
'avgProgress'to the allowedsortByenum. - Left all other parameters intact so existing clients keep working.
Why
- Clients can ask the catalog to rank books by how far readers get, a stronger engagement proxy than simple recency or title.
This DTO change is minimal but important: it creates a typed contract for a new sort dimension without altering route shape. Because validation is centralized here, the service can trust that sortBy='avgProgress' is intentional and safe to handle.
Sorting the Catalog with Query Parameters
To make your catalog more useful, you can let users sort the list of books by different fields. This is done using the sortBy and order query parameters in your API.
Here’s how you might call the endpoint to sort books by title in ascending order:
Or, to sort by avgProgress in descending order:
In your code, this is handled in the findAll method of your service:
Explanation:
- The
sortByparameter lets you choose which field to sort on (liketitle,author, oravgProgress). - The
orderparameter can beasc(ascending) ordesc(descending). - The code sorts the list of books based on your chosen field and order.
Example Output:
If you request /books?sortBy=author&order=asc, you might get:
