NestJS TypeORM Pagination - Demo
When working on an API, sometimes, we have to paginate our data in order to provide a good user experience. In this tutorial, we will be doing a NestJS TypeORM Pagination example. The example will be a products API.
Setting up a NestJS Project
> npm install -g @nestjs/cli
> nest new products-api
Adding TypeORM
If we’re doing pagination, we most probably have a lot of data. And when having a lot of data, we also most probably are storing that data inside a database. To interact with our database we will use TypeORM.
Let’s install and setup the module:
> yarn add @nestjs/typeorm typeorm mysql
I am using MySQL for this example, you can use whichever database you want, you just have to install the correct driver.
Next, let’s import the module in our root module, app.module.ts
:
import {
Module } from '@nestjs/common'
import {
AppController } from './app.controller'
import {
AppService } from './app.service'
import {
TypeOrmModule } from '@nestjs/typeorm'
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'products',
entities: [],
synchronize: true,
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {
}
Creating the Products Module
For this module, we will create a small products module. In order to make thing simple, a product will have on an id
, name
, price
, createdAt
field.
import {
Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class Product {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column(<