evgomes / supermarket-api

Simple RESTful API built with ASP.NET Core and .NET 8 to show how to create RESTful services using a decoupled, maintainable architecture.

Home Page:https://medium.com/free-code-camp/an-awesome-guide-on-how-to-build-restful-apis-with-asp-net-core-87b818123e28

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How about pagination for large result by /api/products?

dundich opened this issue · comments

How to Return a list by array[ID!] (its typical GraphQL scenarios for resolvers)?

Hi @dundich,

I'm sorry for replying so late, I've been traveling and busy with some projects, so I couldn't answer before.

I'm still learning GraphQL, so I can't implement an exactly equal solution, but I changed the /api/products endpoint to allow pagination.

There are plenty of ways of handling this, so I chose a simpler solution to illustrate. We can create a ProductsQueryResource class that will receive the previously added CategoryId, for filtering, and also Page, for indicating in which page we are, and the ItemsPerPage property, that tells the API how many items we want to return per time.

I encapsulated this data into query classes to send to the products service and repository. The trick to page our resulting data is to use the LINQ extensions methods Skip and Take in the repository, with a basic math calculation to return data from the correct page. Also, we have to count the number of items in the database matching the current query, so client applications can use this data to calculate the total number of pages, to display in some nice way to the user (out of scope for the API).

Finally, we can return a QueryResult<T> instance containing the list of items we filtered, and also the total of items in the database.

Remember that there are many ways to implement it, so maybe you end up with a better solution.

Take a look at the new implementation. It's easier to understand it debugging the code, or testing the API using the Swagger UI (last added feature). Don't hesitate to ask me if you don't understand the code or if you have any other doubts.

@all-contributors please add @dundich for ideas

@evgomes

I've put up a pull request to add @dundich! 🎉