Building Generic Pagination and Order in NestJS

Amro Abdalla
2 min readOct 27, 2022

--

This article provides generic pagination and order solution in Nestjs, to be reused with any TypeORM Model. This solution is influenced by the Django framework.

First of all will create a Generic Controller, call it EndPointSet with a list function without pagination:

Then before implementing the pagination, we should create our Query parameters, which are page, pageSize, orderBy, and sortOrder. and the validation of these parameters is made using class-validation and converting the params string values to numbers using class-transformer library:

Then those params can be added to the list function as an argument:

@Get()
public async list(@Query() filter: ListFilter) {...}

In order to activate the validation library, this line has to be added in main.ts to the app object:

app.useGlobalPipes(new ValidationPipe({ transform: true }));

Then we can implement the list function as follows:

Then the Generic Controller can be used with other controller as shown here with Controller for an article entity:

Now we finished 🎉, we can now use the params in the URLs as follows for example to get a paginated response with two items on each page, and the items are ordered according to any field in this case timestamp field descendingly:

localhost:8000/article?orderBy=timestamp&page=1&pageSize=2

This article is part of articles I’m writing about building a generic Controller, you can check the first one here and follow for more 🐈:

--

--