Custom pagination decorator in Nestjs, Pagination has never been easier!!
Published: 2021-11-23 20:23:51

![Pagination](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gy7ohpzqyr2rvq9xu6yj.png)

This tutorial will teach you a good way to make pagination making good use of [Nestjs decorators](https://docs.nestjs.com/custom-decorators). If you have never read about Nestjs framework, I think it's time, once you read the documentation, you would love to use it, Here you can find the [official page](https://nestjs.com/).

Let's not take too much in the introduction and get along with the code!!

_inside terminal_
```
nest new pagination-app
```

this will create a new fresh nestjs app for you, it will ask you for your favorite package module (npm, yarn, ...etc) choose whatever you prefer.


_inside pagination.ts (src/types/)_
```
export interface Pagination {
    skip?:number;
    limit?:number;
    sort?:{ field:string, by:"ASC" | "DESC" }[];
    search?:{ field:string, value:string }[];
}
```
Here we create the pagination interface we expect from the client, these are the most important query parameters that can be sent for pagination.



_inside get-pagination.ts (src/decorators/)_
```
import { createParamDecorator, ExecutionContext } from "@nestjs/common";
import { Request } from "express";
import { Pagination } from "../types/pagination";

export const GetPagination = createParamDecorator((data, ctx:ExecutionContext) : Pagination => {
    const req : Request = ctx.switchToHttp().getRequest();
    
    const paginationParams : Pagination = {
        skip:0,
        limit:10,
        sort:[],
        search:[]
    };

    paginationParams.skip = req.query.skip ? parseInt(req.query.skip.toString()) : 0;
    paginationParams.limit = req.query.limit ? parseInt(req.query.limit.toString()) : 10;

    // create array of sort
    if(req.query.sort){
        const sortArray = req.query.sort.toString().split(',')
        paginationParams.sort = sortArray.map(sortItem => {
            const sortBy = sortItem[0]
            switch (sortBy) {
                case "-":
                    return{
                        field:sortItem.slice(1),
                        by:'ASC'
                    }
                case "+":
                    return{
                        field:sortItem.slice(1),
                        by:'ASC'
                    }
                default:
                    return{
                        field:sortItem.trim(),
                        by:'DESC'
                    }
            }
        })
    }

    // create array of search
    if(req.query.search){
        const searchArray = req.query.search.toString().split(',')
        paginationParams.search = searchArray.map(searchItem => {
            const field = searchItem.split(":")[0]
            const value = searchItem.split(":")[1]
            return {
                field,
                value
            }
        })
    }

    return paginationParams;
})
```
*Here we get the request from the current context, it's very the same as express request object with the same properties it had.
*paginationParams is will contain the default values for the pagination.
*we set the pagination skip and limit based on the query, the ternary operator to check if the limit and skip query parameters can be parsed into numbers.
*for sort, there is many ways to have the field to sort by along with sort order, for me I use **+ for "DESC"** and **- for "ASC"**
*for search, we can separate between the field and the value with a **:**




_inside app-controller.ts (src/)_
```
...
@Get('/cats')
  getCats(@GetPagination() pagination : Pagination): string {
    return this.appService.getCats(pagination);
  }
...
```


_inside app-service.ts (src/)_
```
...
getCats(pagination:Pagination){
    return pagination;
  }
...
```
instead of just returning it, you can have this service connected to the database and query the db according to the values you have, but for simplicity we will just log it to the console.



let's try it, run the app with `npm run start:dev`



let's hit this url > `http://localhost:3000/cats?skip=2&limit=1&search=name:my,age:12&sort=+age`


![Pagination result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m16vluri34we2mdt3fjd.png)


I hope you liked this tutorial, I really advice you to use Nestjs framework, and moreover go read it's documentation! 

Have a nice day :)