Tiếp tục với series, ở bài trước đã có bảng và PrismaService nhưng route vẫn dùng dữ liệu trong bộ nhớ. Bài này mình sẽ giới thiệu với mọi người về CRUD với Prisma trong NestJS: chuyển project và task sang database thật, xử lý lỗi của Prisma và seed dữ liệu.
1. CRUD project với Prisma Client.
Mỗi model có một thuộc tính trên Prisma Client (prisma.project, prisma.task) chứa method CRUD. Các bạn inject PrismaService và thay mảng trong bộ nhớ bằng query:
- src/projects/projects.service.ts
import { Injectable } from '@nestjs/common';
import type { Project } from '../generated/prisma/client.js';
import { PrismaService } from '../prisma/prisma.service.js';
import type { CreateProjectDto } from './dto/create-project.dto.js';
import type { UpdateProjectDto } from './dto/update-project.dto.js';
import { ProjectNotFoundException } from './exceptions/project-not-found.exception.js';
@Injectable()
export class ProjectsService {
constructor(private readonly prisma: PrismaService) {}
findAll(search?: string): Promise<Project[]> {
return this.prisma.project.findMany({
where: search
? { name: { contains: search, mode: 'insensitive' } }
: undefined,
orderBy: { id: 'asc' },
});
}
async findOne(id: number): Promise<Project> {
const project = await this.prisma.project.findUnique({
where: { id },
});
if (!project) {
throw new ProjectNotFoundException(id);
}
return project;
}
findLatest(): Promise<Project | null> {
return this.prisma.project.findFirst({ orderBy: { id: 'desc' } });
}
create(dto: CreateProjectDto): Promise<Project> {
// Tạm gán cho user 1 (tạo bởi seed) tới khi có đăng nhập
return this.prisma.project.create({
data: { name: dto.name, description: dto.description, ownerId: 1 },
});
}
update(id: number, dto: UpdateProjectDto): Promise<Project> {
return this.prisma.project.update({ where: { id }, data: dto });
}
async remove(id: number): Promise<void> {
await this.prisma.project.delete({ where: { id } });
}
}
findMany() lọc bằng where (mode: 'insensitive' giống ILIKE), findUnique() tìm theo cột @id/@unique (không thấy trả về null), create()/update() nhận dữ liệu qua data.
Kiểu Project được generate nên các bạn xoá src/projects/interfaces/project.interface.ts. Controller import Project từ ../generated/prisma/client.js và trả về luôn Promise của service (NestJS tự chờ):
- src/projects/projects.controller.ts (trích)
@Get('latest')
@SkipTransform()
@Redirect('/api/v1/projects', 302)
async findLatest() {
const latest = await this.projectsService.findLatest();
if (latest) {
return { url: `/api/v1/projects/${latest.id}` };
}
}
// findAll(), findOne(), create(), update() cũng return như remove()
@Delete(':id')
@HttpCode(204)
remove(@Param('id', ParseIdPipe) id: number): Promise<void> {
return this.projectsService.remove(id);
}
Chú ý: Handler nào cũng phải return hoặc await Promise của service. Giữ remove() kiểu void của Bài 12 thì tsc vẫn qua, nhưng xoá ID không tồn tại sẽ trả 204 rồi lỗi Prisma thành unhandled rejection làm sập cả app. npm run lint (rule no-floating-promises) bắt được lỗi này.
Lưu ý: Để npm test chạy được, thêm { provide: PrismaService, useValue: {} } vào providers của hai file projects.*.spec.ts (Bài 6), test thật để Bài 34.
2. Seed dữ liệu mẫu.
Project mới thuộc user 1 nên cần có user đó. Seed là script đổ dữ liệu ban đầu. Trước hết mình thêm vào model Project (trên dòng @@map) ràng buộc một người không có hai project trùng tên:
@@unique([ownerId, name])
npx prisma migrate dev --name project_name_unique # hỏi xác nhận thì chọn y
npx prisma generate
Script seed chạy ngoài NestJS nên tự tạo PrismaClient:
- prisma/seed.ts
import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from '../src/generated/prisma/client.js';
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
const prisma = new PrismaClient({ adapter });
try {
// upsert: có rồi thì giữ nguyên (update rỗng), chưa có thì tạo
const user = await prisma.user.upsert({
where: { email: '[email protected]' },
update: {},
create: { name: 'Vu Thanh Tai', email: '[email protected]' },
});
// skipDuplicates: bỏ qua dòng trùng @@unique (đã thêm ở lần seed trước)
const { count } = await prisma.project.createMany({
data: [
{ name: 'Website toidicode.com', ownerId: user.id },
{ name: 'TaskFlow API', ownerId: user.id },
],
skipDuplicates: true,
});
console.log(`Đã thêm ${count} project`);
} finally {
await prisma.$disconnect();
}
Node.js không chạy thẳng được file này (generated client import đuôi .js) nên mình dùng tsx: npm install tsx --save-dev, rồi thêm seed: "tsx prisma/seed.ts", vào khối migrations trong prisma7.config.ts.
npx prisma migrate reset --force # xoá sạch dữ liệu, chạy lại các migration
npx prisma db seed
# Running seed command `tsx prisma/seed.ts` ...
# Đã thêm 2 project
Seed lần nữa sẽ in Đã thêm 0 project. Prisma 7 chỉ seed khi gọi db seed (migrate reset không tự chạy). Muốn về dữ liệu ban đầu, kể cả ID tự tăng, thì chạy lại hai lệnh trên.
3. Đổi lỗi Prisma thành HTTP exception.
Lúc này PATCH /api/v1/projects/99 trả về lỗi 500: update(), delete() không thấy bản ghi thì ném PrismaClientKnownRequestError mã P2025, AllExceptionsFilter coi là lỗi lạ. Mình viết filter đổi mã lỗi Prisma thành HTTP exception (nest g filter common/filters/prisma-exception --no-spec --flat --format):
- src/common/filters/prisma-exception.filter.ts
import {
ArgumentsHost,
BadRequestException,
Catch,
ConflictException,
HttpException,
NotFoundException,
} from '@nestjs/common';
import { Prisma } from '../../generated/prisma/client.js';
import { AllExceptionsFilter } from './all-exceptions.filter.js';
@Catch(Prisma.PrismaClientKnownRequestError)
export class PrismaExceptionFilter extends AllExceptionsFilter {
catch(
exception: Prisma.PrismaClientKnownRequestError,
host: ArgumentsHost,
): void {
// Mã đã biết thành HTTP exception, mã khác để filter cha trả 500
super.catch(this.toHttpException(exception) ?? exception, host);
}
private toHttpException(
exception: Prisma.PrismaClientKnownRequestError,
): HttpException | undefined {
switch (exception.code) {
case 'P2025': // update/delete không tìm thấy bản ghi
return new NotFoundException(
`Không tìm thấy ${String(exception.meta?.modelName)}`,
);
case 'P2002': // vi phạm @unique / @@unique
return new ConflictException('Dữ liệu đã tồn tại');
case 'P2003': // khoá ngoại trỏ tới bản ghi không tồn tại
return new BadRequestException(
'Dữ liệu liên quan không tồn tại',
);
}
}
}
Kế thừa AllExceptionsFilter (Bài 10) nên lỗi vẫn cùng định dạng. Trong src/main.ts phải đăng ký nó sau filter bắt mọi lỗi (đặt ngược lại vẫn ra 500):
app.useGlobalFilters(
new AllExceptionsFilter(),
new PrismaExceptionFilter(),
);
Gọi lại (K là header key):
curl -X PATCH http://localhost:3000/api/v1/projects/99 -H "$K" \
-H "Content-Type: application/json" -d '{"name":"X"}'
# {"statusCode":404,"errorCode":"NOT_FOUND","message":"Không tìm thấy Project",...}
curl http://localhost:3000/api/v1/projects -H "$K" \
-H "Content-Type: application/json" -d '{"name":"TaskFlow API"}'
# {"statusCode":409,"errorCode":"CONFLICT","message":"Dữ liệu đã tồn tại",...}
4. CRUD task.
Task làm tương tự: nest g controller tasks, nest g service tasks (thêm --no-spec --format) và DTO bằng nest g class như Bài 7.
- src/tasks/dto/create-task.dto.ts
import { Type } from 'class-transformer';
import {
IsDate,
IsEnum,
IsInt,
IsNotEmpty,
IsOptional,
IsString,
MaxLength,
} from 'class-validator';
import { TaskStatus } from '../../generated/prisma/client.js';
export class CreateTaskDto {
@IsInt()
projectId: number;
@IsString()
@IsNotEmpty()
@MaxLength(200)
title: string;
@IsOptional()
@IsEnum(TaskStatus)
status?: TaskStatus;
@IsOptional()
@Type(() => Date)
@IsDate()
dueDate?: Date;
}
Enum TaskStatus được generate dùng luôn với @IsEnum(), @Type(() => Date) đổi chuỗi thành Date. UpdateTaskDto là PartialType(CreateTaskDto) (Bài 7).
- src/tasks/tasks.service.ts (trích)
import { Injectable, NotFoundException } from '@nestjs/common';
import type { Task } from '../generated/prisma/client.js';
import { PrismaService } from '../prisma/prisma.service.js';
import type { CreateTaskDto } from './dto/create-task.dto.js';
import type { UpdateTaskDto } from './dto/update-task.dto.js';
@Injectable()
export class TasksService {
constructor(private readonly prisma: PrismaService) {}
async findOne(id: number): Promise<Task> {
const task = await this.prisma.task.findUnique({ where: { id } });
if (!task) {
throw new NotFoundException(`Không tìm thấy task ${id}`);
}
return task;
}
create(dto: CreateTaskDto): Promise<Task> {
return this.prisma.task.create({ data: dto });
}
// findAll() (không search), update(), remove(): như ProjectsService
}
TasksController chép từ bản của project, đổi project thành task, bỏ search, latest, @Header và vẫn return Promise.
curl http://localhost:3000/api/v1/tasks -H "$K" -H "Content-Type: application/json" \
-d '{"projectId":2,"title":"Viết bài CRUD","dueDate":"2026-12-01"}'
# {"data":{"id":1,"title":"Viết bài CRUD",...,"dueDate":"2026-12-01T00:00:00.000Z",...}}
curl http://localhost:3000/api/v1/tasks -H "$K" -H "Content-Type: application/json" \
-d '{"projectId":99,"title":"Lạc đề"}'
# {"statusCode":400,"errorCode":"BAD_REQUEST","message":"Dữ liệu liên quan không tồn tại",...}
Project 99 không tồn tại nên khoá ngoại báo lỗi P2003. Thử xong các bạn chạy lại migrate reset --force và db seed.
Lưu ý: PATCH với giá trị null như {"title":null} (task) hay {"description":null} (project) hiện vẫn ra lỗi 500, Bài 17 sẽ xử lý.
5. Lời kết.
Như vậy mình đã giới thiệu với mọi người về CRUD với Prisma trong NestJS: các method CRUD, đổi lỗi Prisma thành 404/409/400 và seed dữ liệu. Bài sau là quan hệ dữ liệu với Prisma để lấy project kèm task, task kèm tag.
Đă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