Tiếp tục với series, ở bài trước mỗi route chỉ trả về dữ liệu của một bảng. Bài này mình sẽ giới thiệu với mọi người về quan hệ dữ liệu với Prisma trong NestJS: tag cho task, lấy project kèm task, transaction và tránh lỗi N+1.
1. Quan hệ 1-n và n-n trong schema.prisma.
Ở Bài 15 đã có quan hệ 1-n: một project có nhiều task. Phía "nhiều" giữ khoá ngoại projectId và relation field project có @relation(fields: [projectId], references: [id]), phía "một" chỉ có tasks Task[], không tạo cột.
Một task có nhiều tag, một tag gắn cho nhiều task: đó là quan hệ n-n. Các bạn thêm model Tag và dòng tags Tag[] vào model Task (trên dòng createdAt):
- prisma/schema.prisma (đoạn trích)
model Tag {
id Int @id @default(autoincrement())
name String @unique @db.VarChar(30)
tasks Task[]
@@map("tags")
}
npx prisma migrate dev --name tags
npx prisma generate
Hai phía đều là danh sách nên đây là n-n ngầm định (implicit): Prisma tự tạo bảng trung gian _TagToTask (cột A: id tag, B: id task). Bảng trung gian cần thêm cột (VD ngày gắn) thì mới tự viết model cho nó.
2. Nested write: gắn tag khi tạo task.
Tag được gửi lên dưới dạng mảng tên:
- src/tasks/dto/create-task.dto.ts (đoạn trích, thêm ArrayMaxSize, ArrayUnique, IsArray, ValidateIf vào import)
// Bỏ qua khi không gửi, nhưng vẫn validate khi gửi null (cột không nhận null)
const isDefined = (_: object, value: unknown) => value !== undefined;
export class CreateTaskDto {
// ...
@ValidateIf(isDefined)
@IsArray()
@ArrayMaxSize(10)
@ArrayUnique()
@IsString({ each: true })
@IsNotEmpty({ each: true })
@MaxLength(30, { each: true })
tags?: string[];
}
Lưu ý: @IsOptional() bỏ qua cả null, nên PATCH project với {"description":null} lọt validation rồi bị Prisma từ chối (500). Mình đổi @IsOptional() của description (CreateProjectDto) và status thành @ValidateIf((_, value) => value !== undefined), UpdateTaskDto thêm { skipNullProperties: false } như Bài 8. Giờ null nhận 400, riêng dueDate vẫn nhận null.
Nested write là ghi dữ liệu của bảng liên quan ngay trong create()/update():
- src/tasks/tasks.service.ts (đoạn trích, import type { Prisma } từ ../generated/prisma/client.js)
// Trả kèm mọi tag, project chỉ lấy id và name
const taskInclude = {
tags: true,
project: { select: { id: true, name: true } },
} satisfies Prisma.TaskInclude;
export type TaskWithRelations = Prisma.TaskGetPayload<{
include: typeof taskInclude;
}>;
// Trong class TasksService:
create(dto: CreateTaskDto): Promise<TaskWithRelations> {
const { tags, ...data } = dto;
return this.prisma.task.create({
data: { ...data, tags: tags && this.connectTags(tags) },
include: taskInclude,
});
}
update(id: number, dto: UpdateTaskDto): Promise<TaskWithRelations> {
const { tags, ...data } = dto;
return this.prisma.task.update({
where: { id },
// Gỡ hết tag cũ rồi gắn danh sách mới
data: {
...data,
tags: tags && { set: [], ...this.connectTags(tags) },
},
include: taskInclude,
});
}
// Tag đã có thì nối vào task, chưa có thì tạo mới
private connectTags(names: string[]) {
return {
connectOrCreate: names.map((name) => ({
where: { name },
create: { name },
})),
};
}
Trong đó:
connectOrCreate: tìm tag theo cột uniquename, có thì nối, chưa có thì tạo. Ngoài ra còncreate,connect,disconnect.set: []: gỡ mọi tag cũ (xoá dòng trong_TagToTask, không xoá tag); không gửitagsthì Prisma bỏ qua trường này.
findAll(), findOne() cũng thêm include: taskInclude; trong service và TasksController đổi kiểu Task thành TaskWithRelations. Reset dữ liệu (npx prisma migrate reset --force rồi npx prisma db seed) và thử:
curl http://localhost:3000/api/v1/tasks -H "$K" -H "Content-Type: application/json" \
-d '{"projectId":2,"title":"Viết bài quan hệ dữ liệu","tags":["prisma","backend"]}'
# {"data":{"id":1,...,"tags":[{"id":1,"name":"prisma"},{"id":2,"name":"backend"}],"project":{"id":2,"name":"TaskFlow API"}}}
curl http://localhost:3000/api/v1/tasks -H "$K" -H "Content-Type: application/json" \
-d '{"projectId":1,"title":"Sửa giao diện","tags":["frontend","prisma"]}'
# {"data":{"id":2,...,"tags":[{"id":1,"name":"prisma"},{"id":3,"name":"frontend"}],...}}
curl -X PATCH http://localhost:3000/api/v1/tasks/2 -H "$K" \
-H "Content-Type: application/json" -d '{"tags":["frontend"]}'
# {"data":{"id":2,...,"tags":[{"id":3,"name":"frontend"}],...}}
Tag prisma được dùng lại (id 1). Nested write chạy trong một transaction.
3. Lấy dữ liệu liên quan với include và select.
Mặc định Prisma chỉ trả về các cột của model. include lấy thêm relation field, select chỉ lấy các trường được chọn (không dùng chung với include ở cùng cấp), _count đếm bản ghi liên quan. Ở trên taskInclude lấy mọi tag nhưng chỉ id, name của project; satisfies kiểm tra kiểu, TaskGetPayload sinh kiểu kết quả. Với project:
- src/projects/projects.service.ts (đoạn trích)
import type { Prisma, Project } from '../generated/prisma/client.js';
const projectDetail = {
tasks: {
select: { id: true, title: true, status: true },
orderBy: { id: 'asc' },
},
} satisfies Prisma.ProjectInclude;
export type ProjectDetail = Prisma.ProjectGetPayload<{
include: typeof projectDetail;
}>;
export type ProjectWithCount = Prisma.ProjectGetPayload<{
include: { _count: { select: { tasks: true } } };
}>;
// findAll(): thêm vào findMany()
include: { _count: { select: { tasks: true } } },
// findOne(): thêm vào findUnique()
include: projectDetail,
Hai kiểu ProjectDetail, ProjectWithCount dùng làm kiểu trả về cho cả service và ProjectsController.
curl http://localhost:3000/api/v1/projects -H "$K"
# {"data":[{"id":1,...,"_count":{"tasks":1}},{"id":2,...,"_count":{"tasks":1}}]}
curl http://localhost:3000/api/v1/projects/2 -H "$K"
# {"data":{"id":2,"name":"TaskFlow API",...,"tasks":[{"id":1,"title":"Viết bài quan hệ dữ liệu","status":"todo"}]}}
4. Transaction với $transaction.
Transaction là nhóm câu lệnh cùng thành công hoặc cùng thất bại. Thao tác không gộp được vào một nested write thì dùng $transaction(). VD: xoá project nhưng giữ task với DELETE /projects/:id?moveTasksTo=2:
- src/projects/projects.service.ts (đoạn trích, thêm BadRequestException vào import)
async remove(id: number, moveTasksTo?: number): Promise<void> {
if (moveTasksTo === undefined) {
// onDelete: Cascade xoá luôn các task của project
await this.prisma.project.delete({ where: { id } });
return;
}
if (moveTasksTo === id) {
throw new BadRequestException('moveTasksTo phải khác id');
}
// Lỗi ở bước nào cũng huỷ cả hai bước
await this.prisma.$transaction([
this.prisma.task.updateMany({
where: { projectId: id },
data: { projectId: moveTasksTo },
}),
this.prisma.project.delete({ where: { id } }),
]);
}
Các query trong mảng chạy lần lượt trong một transaction: delete() lỗi sau khi task đã chuyển thì Prisma ROLLBACK, task về chỗ cũ. remove() của ProjectsController nhận thêm @Query('moveTasksTo', { schema: z.coerce.number().int().min(1).optional() }) moveTasksTo?: number và truyền vào service.
curl -X DELETE "http://localhost:3000/api/v1/projects/1?moveTasksTo=2" -H "$K" -i
# HTTP/1.1 204 No Content
curl -X DELETE "http://localhost:3000/api/v1/projects/2?moveTasksTo=99" -H "$K"
# {"statusCode":400,"errorCode":"BAD_REQUEST","message":"Dữ liệu liên quan không tồn tại",...}
Lần thứ hai project 99 không tồn tại, updateMany() lỗi khoá ngoại nên project 2 vẫn còn. Khi bước sau cần kết quả bước trước thì dùng dạng interactive $transaction(async (tx) => { ... }): query đi qua tx, hàm ném lỗi là rollback (mặc định tối đa 5 giây).
5. Tránh N+1.
Lỗi N+1: một query lấy N bản ghi, rồi thêm một query cho mỗi bản ghi. VD:
// Đừng làm thế này: 1 query lấy task + N query lấy tag
const tasks = await this.prisma.task.findMany();
for (const task of tasks) {
const tags = await this.prisma.tag.findMany({
where: { tasks: { some: { id: task.id } } },
});
Object.assign(task, { tags });
}
Để đếm query, tạm sửa super({ adapter }) trong PrismaService thành super({ adapter, log: ['query'] }) rồi gọi GET /api/v1/tasks (đang có 2 task):
# Vòng lặp: 1 + 2 query
prisma:query SELECT ... FROM "public"."tasks" ...
prisma:query SELECT ... FROM "public"."tags" WHERE EXISTS(...) ...
prisma:query SELECT ... FROM "public"."tags" WHERE EXISTS(...) ...
# include: luôn 3 query (task, tag, project)
prisma:query SELECT ... FROM "public"."tasks" ...
prisma:query SELECT ... FROM "public"."tags" INNER JOIN "public"."_TagToTask" ... "t0"."B" IN ($1,$2) ...
prisma:query SELECT ... FROM "public"."projects" WHERE "public"."projects"."id" IN ($1,$2) ...
Với include, mỗi relation chỉ cần một query IN (...) cho mọi task, nên đừng query trong vòng lặp. Xem xong bỏ log.
6. Lời kết.
Như vậy mình đã giới thiệu với mọi người về quan hệ dữ liệu với Prisma trong NestJS: 1-n, n-n, nested write, include/select, $transaction và N+1. Hiện GET /projects trả về tất cả project, bài sau mình sẽ giới thiệu về phân trang, lọc và sắp xếp trong NestJS.
Đă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