First lets install this incredible package
Installation
npm install nestjs-paginate
Now our Endpoint should look something like that
http://localhost:3000/cats?limit=5&page=2&sortBy=color:DESC&search=i&filter.age=$gte:3&select=id,name,color,age
And the result should look like that
{
"data": [
{
"id": 4,
"name": "George",
"color": "white",
"age": 3
},
{
"id": 5,
"name": "Leche",
"color": "white",
"age": 6
},
{
"id": 2,
"name": "Garfield",
"color": "ginger",
"age": 4
},
{
"id": 1,
"name": "Milo",
"color": "brown",
"age": 5
},
{
"id": 3,
"name": "Kitty",
"color": "black",
"age": 3
}
],
"meta": {
"itemsPerPage": 5,
"totalItems": 12,
"currentPage": 2,
"totalPages": 3,
"sortBy": [["color", "DESC"]],
"search": "i",
"filter": {
"age": "$gte:3"
}
},
"links": {
"first": "http://localhost:3000/cats?limit=5&page=1&sortBy=color:DESC&search=i&filter.age=$gte:3",
"previous": "http://localhost:3000/cats?limit=5&page=1&sortBy=color:DESC&search=i&filter.age=$gte:3",
"current": "http://localhost:3000/cats?limit=5&page=2&sortBy=color:DESC&search=i&filter.age=$gte:3",
"next": "http://localhost:3000/cats?limit=5&page=3&sortBy=color:DESC&search=i&filter.age=$gte:3",
"last": "http://localhost:3000/cats?limit=5&page=3&sortBy=color:DESC&search=i&filter.age=$gte:3"
}
}
Now lets find how to set up our code
The Entity
import { Column, Entity } from 'typeorm';
@Entity()
export class CommodityEntity extends AbstractSharedEntity {
@Column({ length: 500 })
name: string;
@Column({ length: 50 })
icon: string;
}
The Controller
...
import { Paginate, PaginateQuery } from 'nestjs-paginate';
...
async findAll(@Query() where: any, @Paginate() query: PaginateQuery) {
return await this.commodityService.findAll(query);
}
...
The Service
...
import { FilterOperator, FilterSuffix, PaginateQuery, paginate } from 'nestjs-paginate';
...
public async findAll(query: PaginateQuery): Promise<any> {
return paginate(query, this.commodityRepository.getRepository(), {
sortableColumns: ['id', 'created_at'],
nullSort: 'last',
withDeleted: !!query?.filter?.deleted_at,
searchableColumns: ['name'],
select: ['name', 'icon', 'created_at', 'isActive', 'deleted_at'],
filterableColumns: {
name: [FilterOperator.CONTAINS, FilterOperator.EQ],
isActive: [FilterOperator.EQ],
deleted_at: [FilterSuffix.NOT, FilterOperator.NULL],
},
});
}
...
Top comments (0)