Tiếp tục với series, ở bài trước GET /projects và GET /tasks vẫn trả về toàn bộ bản ghi. Bài này mình sẽ giới thiệu với mọi người về phân trang, lọc và sắp xếp trong NestJS: DTO cho query string, phân trang bằng skip/take và bằng cursor.
1. DTO cho query string.
Thay vì mỗi tham số một DefaultValuePipe, ParseIntPipe như Bài 9, mình gom chúng vào một DTO cho ValidationPipe toàn cục kiểm tra. Các file mới các bạn tạo bằng nest g class <đường dẫn, bỏ .ts> --no-spec --flat --format như Bài 7.
- src/common/pagination/pagination-query.dto.ts
import { Type } from 'class-transformer';
import { IsInt, Max, Min } from 'class-validator';
export class PaginationQueryDto {
// Query string luôn là chuỗi: @Type đổi sang số trước khi validate
@Type(() => Number)
@IsInt()
@Min(1)
@Max(1000) // Trang quá sâu thì dùng cursor (offset lớn chạy chậm)
page: number = 1;
@Type(() => Number)
@IsInt()
@Min(1)
@Max(100)
limit: number = 10;
}
Trong đó:
@Type(() => Number):transform: truekhông tự đổi kiểu thuộc tính của DTO. Thiếu nó,?page=2bị lỗipage must be an integer number.- Giá trị gán sẵn (
= 1,= 10) là mặc định khi không gửi. @Max: không giới hạn thì?limit=1000000kéo cả bảng về, còn?page=1e20làm Prisma lỗi 500.
Lưu ý: Đừng dùng @Type(() => Boolean) vì chuỗi "false" sẽ thành true; hãy so sánh chuỗi trong @Transform.
2. Lọc và sắp xếp theo danh sách cho phép.
Tham số sort có dạng ?sort=-name (giảm dần). Đưa thẳng chuỗi client gửi vào orderBy thì ai cũng sắp xếp được theo cột bất kỳ, tên cột sai thì lỗi 500. Mình dùng một allow-list vừa để validate vừa ánh xạ sang orderBy:
- src/projects/dto/list-projects-query.dto.ts
import { IsIn, IsOptional, IsString, MaxLength } from 'class-validator';
import { PaginationQueryDto } from '../../common/pagination/pagination-query.dto.js';
import type { Prisma } from '../../generated/prisma/client.js';
// Chỉ cho sắp xếp theo các cột trong danh sách này (dấu - là giảm dần)
export const PROJECT_SORTS = {
id: { id: 'asc' },
'-id': { id: 'desc' },
name: { name: 'asc' },
'-name': { name: 'desc' },
createdAt: { createdAt: 'asc' },
'-createdAt': { createdAt: 'desc' },
} satisfies Record<string, Prisma.ProjectOrderByWithRelationInput>;
export class ListProjectsQueryDto extends PaginationQueryDto {
@IsOptional()
@IsString()
@MaxLength(50)
search?: string;
@IsIn(Object.keys(PROJECT_SORTS))
sort: keyof typeof PROJECT_SORTS = 'id';
}
search chuyển từ schema Zod vào DTO. Nhờ forbidNonWhitelisted, tham số lạ (?foo=1) bị từ chối.
3. Phân trang với skip/take và trả meta.
Phân trang theo số trang (offset): bỏ qua (page - 1) * limit bản ghi (skip) rồi lấy limit bản ghi (take). Client cần biết tổng số bản ghi nên response có dạng { data, meta }:
- src/common/pagination/paginated.ts
export interface PageMeta {
page: number;
limit: number;
total: number;
totalPages: number;
}
export interface CursorMeta {
limit: number;
nextCursor: number | null;
}
// Kết quả có phân trang: TransformInterceptor trả nguyên, không bọc thêm { data }
export class Paginated<T, M extends PageMeta | CursorMeta> {
constructor(
readonly data: T[],
readonly meta: M,
) {}
}
TransformInterceptor (Bài 13) sẽ bọc { data, meta } thành { data: { data, meta } }, nên mình sửa để nó trả nguyên object Paginated:
- src/common/interceptors/transform.interceptor.ts (đoạn trích, import Paginated từ ../pagination/paginated.js)
// Kết quả phân trang đã có sẵn data và meta: trả nguyên
return next
.handle()
.pipe(map((data) => (data instanceof Paginated ? data : { data })));
Service lấy trang và đếm tổng trong một $transaction (Bài 17):
- src/projects/projects.service.ts (đoạn trích, thêm import Paginated, type PageMeta, PROJECT_SORTS, type ListProjectsQueryDto)
async findAll(
query: ListProjectsQueryDto,
): Promise<Paginated<ProjectWithCount, PageMeta>> {
const { page, limit, search, sort } = query;
const where: Prisma.ProjectWhereInput = search
? { name: { contains: search, mode: 'insensitive' } }
: {};
const [projects, total] = await this.prisma.$transaction([
this.prisma.project.findMany({
where,
include: { _count: { select: { tasks: true } } },
// Thêm id để thứ tự luôn cố định khi cột sắp xếp trùng giá trị
orderBy: [PROJECT_SORTS[sort], { id: 'asc' }],
skip: (page - 1) * limit,
take: limit,
}),
this.prisma.project.count({ where }),
]);
return new Paginated(projects, {
page,
limit,
total,
totalPages: Math.ceil(total / limit),
});
}
findAll() của ProjectsController nhận @Query() query: ListProjectsQueryDto (import DTO như giá trị, không import type) và trả về Promise<Paginated<ProjectWithCount, PageMeta>>. Reset dữ liệu (npx prisma migrate reset --force, npx prisma db seed), tạo thêm 5 project và thử:
for name in Blog "Mobile app" CRM "Landing page" Docs; do
curl -s http://localhost:3000/api/v1/projects -H "$K" \
-H "Content-Type: application/json" -d "{\"name\":\"$name\"}" > /dev/null
done
curl "http://localhost:3000/api/v1/projects?limit=2&page=2" -H "$K"
# {"data":[{"id":3,"name":"Blog",...},{"id":4,"name":"Mobile app",...}],"meta":{"page":2,"limit":2,"total":7,"totalPages":4}}
curl "http://localhost:3000/api/v1/projects?search=a&sort=-name&limit=2" -H "$K"
# {"data":[{"id":2,"name":"TaskFlow API",...},{"id":4,"name":"Mobile app",...}],"meta":{"page":1,"limit":2,"total":3,"totalPages":2}}
curl "http://localhost:3000/api/v1/projects?sort=ownerId" -H "$K"
# {"statusCode":400,...,"message":["sort must be one of the following values: id, -id, name, -name, createdAt, -createdAt"],...}
4. Phân trang bằng cursor và lọc task.
Với offset, database vẫn đọc qua mọi bản ghi bị skip, và nếu có bản ghi thêm/xoá giữa hai lần gọi thì trang sau bị lặp hoặc sót. Phân trang bằng cursor lấy các bản ghi có id lớn hơn id cuối của trang trước, đổi lại không nhảy thẳng tới trang 5 được. Task dùng cách này, kèm bộ lọc status:
- src/tasks/dto/list-tasks-query.dto.ts
import { PickType } from '@nestjs/mapped-types';
import { Type } from 'class-transformer';
import { IsEnum, IsInt, IsOptional, Max, Min } from 'class-validator';
import { PaginationQueryDto } from '../../common/pagination/pagination-query.dto.js';
import { TaskStatus } from '../../generated/prisma/client.js';
// Lấy lại limit (kèm validation và giá trị mặc định), không dùng page
export class ListTasksQueryDto extends PickType(PaginationQueryDto, [
'limit',
] as const) {
// id của task cuối cùng ở trang trước
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
@Max(2_147_483_647) // Giá trị lớn nhất của cột Int (PostgreSQL)
cursor?: number;
@IsOptional()
@IsEnum(TaskStatus)
status?: TaskStatus;
}
- src/tasks/tasks.service.ts (đoạn trích, import Paginated, type CursorMeta và type ListTasksQueryDto)
async findAll(
query: ListTasksQueryDto,
): Promise<Paginated<TaskWithRelations, CursorMeta>> {
const { limit, cursor, status } = query;
const tasks = await this.prisma.task.findMany({
// Trường undefined (không lọc) được Prisma bỏ qua
where: { status, id: cursor ? { gt: cursor } : undefined },
include: taskInclude,
orderBy: { id: 'asc' },
// Lấy dư 1 bản ghi để biết còn trang sau hay không
take: limit + 1,
});
const hasMore = tasks.length > limit;
const data = tasks.slice(0, limit);
return new Paginated(data, {
limit,
nextCursor: hasMore ? data[data.length - 1].id : null,
});
}
Cột làm cursor phải unique và là cột sắp xếp, ở đây là id. Prisma có option cursor: { id } + skip: 1, nhưng nó trả mảng rỗng khi task làm cursor đã bị xoá hoặc không còn khớp bộ lọc, nên mình dùng id > cursor. TasksController.findAll() nhận @Query() query: ListTasksQueryDto như project. Tạo 5 task rồi thử:
for s in todo doing done todo doing; do
curl -s http://localhost:3000/api/v1/tasks -H "$K" -H "Content-Type: application/json" \
-d "{\"projectId\":2,\"title\":\"Task $s\",\"status\":\"$s\"}" > /dev/null
done
curl "http://localhost:3000/api/v1/tasks?limit=2" -H "$K"
# {"data":[{"id":1,...},{"id":2,...}],"meta":{"limit":2,"nextCursor":2}}
curl "http://localhost:3000/api/v1/tasks?limit=2&cursor=2" -H "$K"
# {"data":[{"id":3,...},{"id":4,...}],"meta":{"limit":2,"nextCursor":4}}
curl "http://localhost:3000/api/v1/tasks?status=todo&limit=1&cursor=1" -H "$K"
# {"data":[{"id":4,"title":"Task todo","status":"todo",...}],"meta":{"limit":1,"nextCursor":null}}
nextCursor bằng null là đã hết dữ liệu, ?status=pending hay ?limit=500 nhận lỗi 400.
5. Lời kết.
Như vậy mình đã giới thiệu với mọi người về phân trang, lọc và sắp xếp trong NestJS: DTO cho query, allow-list cho sort, skip/take với meta và phân trang bằng cursor. Bài sau mình sẽ giới thiệu về MongoDB với Mongoose trong NestJS, dùng để lưu nhật ký hoạt động.
Đăng ký nhận tin.
Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!





0 Comments