Learn how to implement pagination and search functionality in a NestJS application using Sequelize ORM. This guide covers step-by-step instructions with examples, and also includes common interview questions and answers on the topic.
Imagine you’re looking for your favorite books in a library with thousands of them! It would be really hard to find one specific book if all of them were piled together in one huge heap. Now, imagine the librarian gives you a few books at a time and lets you search through them. That’s exactly what we’re going to do in our web application — we’ll use pagination to show only a few items at a time and a search function to find exactly what you’re looking for.
In this blog, we’ll learn how to add pagination and search functionality to a NestJS app using the Sequelize ORM to interact with a database. Don’t worry, we’ll keep it simple and clear!
Table of Contents
What is Pagination and Search?
- Pagination is when we break down a large list of items (like books or movies) into smaller chunks, so we don’t have to show everything at once. Think of it as flipping through pages of a book instead of reading it all in one go.
- Search is like having a magic wand where you can look for specific items in the list, so you don’t have to look through everything manually. It helps you find things quickly!
Steps to Implement Pagination and Search in NestJS with Sequelize ORM
Step 1: Setting Up NestJS with Sequelize
Before we can use Sequelize for interacting with the database, we need to set up NestJS and Sequelize. Here’s how:
- Install the required packages:
npm install @nestjs/sequelize sequelize sequelize-typescript mysql2
- Set up your database connection in
app.module.ts
:import { Module } from '@nestjs/common';
import { SequelizeModule } from '@nestjs/sequelize';
import { Book } from './book.model';
@Module({ imports:
[ SequelizeModule.forRoot({ dialect: 'mysql', host: 'localhost', port: 3306, username: 'root', password: 'password', database: 'library', models: [Book], }), ], })
export class AppModule {}
Step 2: Create a Model for Your Data
Let’s say you’re building a book store. We need to create a Book
model to store the books in our database. A model tells Sequelize how to handle the data.
import { Column, Model, Table } from 'sequelize-typescript';
@Table
export class Book extends Model {
@Column
title: string;
@Column
author: string;
@Column
description: string;
}
This is a simple model with three columns: title
, author
, and description
.
Step 3: Implement Search and Pagination in the Service
Now, let’s create a service where we handle the logic for searching and paginating the books.
- Search: We’ll allow searching by the book title or author.
- Pagination: We’ll limit how many books we show per page and allow users to navigate between pages.
Here’s how you can do it:
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { Book } from './book.model';
@Injectable()
export class BookService {
constructor(
@InjectModel(Book)
private bookModel: typeof Book,
) {}
async findAll(page: number, limit: number, search: string) {
const offset = (page - 1) * limit;
const books = await this.bookModel.findAll({
where: {
title: {
[Op.like]: `%${search}%`, // Search for titles containing the search keyword
},
},
offset: offset,
limit: limit,
});
return books;
}
}
In this code:
- We use
Op.like
to search for books that contain the search term in their title. - Pagination is handled by calculating the
offset
, which tells the database where to start fetching results.
Step 4: Expose the Search and Pagination in the Controller
Now, let’s create a controller that will handle HTTP requests from users.
import { Controller, Get, Query } from '@nestjs/common';
import { BookService } from './book.service';
@Controller('books')
export class BookController {
constructor(private readonly bookService: BookService) {}
@Get()
async findAll(
@Query('page') page: number = 1,
@Query('limit') limit: number = 10,
@Query('search') search: string = '',
) {
return this.bookService.findAll(page, limit, search);
}
}
@Query()
decorators allow us to get query parameters likepage
,limit
, andsearch
from the URL.- By default, we show the first page with 10 items per page if no query parameters are passed.
Step 5: Testing the API
Now, you can test your API by sending requests to your NestJS app.
- Search books:bashCopy code
GET http://localhost:3000/books?search=Harry
- Paginate results:bashCopy code
GET http://localhost:3000/books?page=2&limit=5
Interview Questions and Answers
Q1: What is the purpose of using Sequelize ORM in NestJS?
A1: Sequelize is an Object-Relational Mapping (ORM) library that helps us interact with databases using JavaScript objects instead of writing raw SQL queries. It simplifies database operations like querying, inserting, updating, and deleting data.
Q2: How do you implement pagination in a NestJS service with Sequelize?
A2: In NestJS, pagination can be implemented by calculating the offset
and limit
based on the page
and limit
query parameters. The offset
is (page - 1) * limit
, which tells Sequelize where to start fetching the results. The limit
is the number of items to return per page.
Q3: How does Sequelize handle search functionality?
A3: Sequelize uses operators like Op.like
to perform search operations. Op.like
allows us to search for records that contain a certain substring. For example, title: { [Op.like]: '%search%' }
would return all books whose title contains the word search
.
Q4: What are some common issues faced when implementing pagination in Sequelize?
A4: Some common issues include:
- Incorrectly calculating the
offset
value, leading to the wrong set of results. - Returning too many results due to improper use of
limit
. - Missing validation for
page
andlimit
parameters, which can cause errors or performance issues.
Companies That Ask About This Topic in Interviews
Here are some companies that commonly ask about implementing pagination and search functionality with NestJS and Sequelize:
- Turing
- Zomato
- Tech Mahindra
- Globant
- Wipro
These companies often look for developers who can handle back-end tasks involving data handling and optimization, like implementing search and pagination.
Conclusion
In this blog, we learned how to implement pagination and search functionality in a NestJS application using Sequelize ORM. Pagination helps us break large lists into smaller, manageable chunks, and search lets us find specific items quickly. With the steps above, you can easily integrate these features into your NestJS projects, making them more efficient and user-friendly.
Happy coding!