DEV Community

Omar Elwakeel
Omar Elwakeel

Posted on

Custom pagination decorator in Nestjs, Pagination has never been easier!!

Pagination

This tutorial will teach you a good way to make pagination making good use of Nestjs 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.

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

inside terminal



nest new pagination-app


Enter fullscreen mode Exit fullscreen mode

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 }[];
}


Enter fullscreen mode Exit fullscreen mode

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;
})


Enter fullscreen mode Exit fullscreen mode

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);
  }
...


Enter fullscreen mode Exit fullscreen mode

inside app-service.ts (src/)



...
getCats(pagination:Pagination){
    return pagination;
  }
...


Enter fullscreen mode Exit fullscreen mode

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

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 :)

Top comments (0)