NestJS & kiến trúc backend: DI, module, clean architecture
Framework backend Node phổ biến nhất ở công ty lớn: module, provider, DI, request pipeline (middleware → guard → interceptor → pipe → handler → filter), và cách giữ nghiệp vụ sạch khỏi framework.
Khi team lên 5-20 backend dev, "Express tự do" thành mỗi người một kiểu. NestJS áp đặt cấu trúc
(giống Spring/ASP.NET), nên nó xuất hiện dày trong JD Node.js lương cao, đặc biệt ở công ty làm cho thị trường
Mỹ/Âu/Nhật và fintech. Nhưng NestJS cũng dễ bị dùng sai: controller béo, mọi thứ là @Injectable,
nghiệp vụ dính chặt decorator. Module này dạy cả framework lẫn cách không để framework nuốt mất thiết kế.
🎯 Mục tiêu học tập
- Hiểu Inversion of Control và Dependency Injection, vì sao chúng giúp test
- Dùng module, provider, controller; hiểu scope của provider
- Nắm thứ tự request pipeline; viết guard, interceptor, pipe, exception filter
- Cấu hình theo môi trường, validate input
- Áp dụng clean/hexagonal architecture và DDD-lite ở mức vừa phải
DI và module
@Module({
imports: [DatabaseModule],
controllers: [ProjectsController],
providers: [
ProjectsService,
{ provide: PROJECT_REPO, useClass: PrismaProjectRepository }, // inject theo token → dễ thay khi test
],
exports: [ProjectsService],
})
export class ProjectsModule {}
@Injectable()
export class ProjectsService {
constructor(
@Inject(PROJECT_REPO) private readonly repo: ProjectRepository, // phụ thuộc vào interface
private readonly events: EventEmitter2,
) {}
}
Provider mặc định là singleton. Scope REQUEST tạo instance mới mỗi
request và "lây" lên mọi thứ phụ thuộc vào nó — chậm, chỉ dùng khi thật cần (thường thay bằng
AsyncLocalStorage/nestjs-cls cho context như tenantId).
Request pipeline
Request
→ Middleware (requestId, logging, cookie-parser)
→ Guards (có được vào không? AuthGuard, RolesGuard)
→ Interceptors (trước) (đo thời gian, cache, transform)
→ Pipes (validate & transform tham số)
→ Controller handler → Service
→ Interceptors (sau) (map response, serialize)
→ Exception filters (bắt lỗi → response chuẩn)
Response
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(ctx: ExecutionContext): boolean {
const required = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [ctx.getHandler(), ctx.getClass()]);
if (!required) return true;
const { user } = ctx.switchToHttp().getRequest();
return required.some((r) => user?.roles.includes(r));
}
}
@Post(':id/archive')
@Roles('owner', 'admin')
archive(@Param('id', ParseUUIDPipe) id: string, @CurrentUser() user: AuthUser) {
return this.projects.archive(id, user);
}
Clean / hexagonal architecture vừa đủ
modules/billing/
├── domain/ # entity, value object, quy tắc nghiệp vụ — KHÔNG import NestJS, Prisma
│ ├── invoice.ts
│ └── money.ts
├── application/ # use case: CreateInvoice, PayInvoice; định nghĩa port (interface)
│ └── ports/invoice.repository.ts
├── infrastructure/ # adapter: PrismaInvoiceRepository, StripePaymentGateway
└── presentation/ # controller, DTO
| Mức | Khi nào |
|---|---|
| Controller → Service → ORM trực tiếp | CRUD đơn giản, admin panel. Đừng ngại — đa số module là vậy |
| Service + repository interface | Cần test service không có DB, có thể đổi nguồn dữ liệu |
| Domain model + use case + port/adapter | Nghiệp vụ phức tạp: billing, đặt chỗ, kho hàng, quy tắc hay thay đổi |
Áp hexagonal cho một endpoint CRUD là tốn gấp 4 số file mà không được gì. Senior là người biết chỗ nào cần lớp trừu tượng, không phải người thêm nó ở mọi nơi.
Cấu hình, event nội bộ và các module hay dùng
@nestjs/config+ Zod validate env khi khởi động.@nestjs/event-emittercho domain event trong cùng tiến trình (OrderPaid → gửi email, cập nhật thống kê) — giảm phụ thuộc chéo giữa module.@nestjs/schedulecho cron;@nestjs/bullmqcho queue (Module 7);@nestjs/terminuscho health check.@nestjs/swaggersinh OpenAPI; hoặcnestjs-zodđể giữ Zod làm nguồn sự thật.- Test:
Test.createTestingModulevớioverrideProviderđể thay repository bằng fake.
🏋️ Bài tập thực hành
Viết lại API Project/Task bằng NestJS: một module cho mỗi tính năng, repository inject theo
token, RolesGuard + decorator @Roles, interceptor đo thời gian và gắn vào log,
exception filter trả Problem Details, health check /health. Viết unit test cho service bằng
fake repository (không DB) và e2e test cho controller. Ghi file docs/adr/001.md giải thích vì
sao module Task dùng service + repository còn module Billing (ở capstone) cần domain model.
📚 Tài nguyên học tập
-
NestJS DocumentationĐọc hết phần Overview và FundamentalsDocs
-
NestJS — Request lifecycleThứ tự middleware, guard, interceptor, pipe, filterDocs
-
Domain-Driven Design Distilled (Vaughn Vernon)Nhập môn DDD ngắn gọnSách
-
nestjs-clsContext theo request bằng AsyncLocalStorageRepo
✅ Tự đánh giá hoàn thành
- Giải thích được DI và vì sao inject theo interface giúp test
- Vẽ được request pipeline của NestJS theo đúng thứ tự
- Viết được guard, interceptor, pipe, exception filter
- Biết khi nào CRUD đơn giản là đủ, khi nào cần domain model