Dưới đây là hướng dẫn chi tiết về cấu trúc dự án chuẩn hóa (standardized project structure) trong NestJS. NestJS khuyến khích một cách tiếp cận modular, nơi mỗi tính năng (feature) được tổ chức trong module riêng biệt để dễ quản lý, mở rộng và bảo trì. Cấu trúc này không phải là bắt buộc 100% (vì NestJS linh hoạt), nhưng đây là mô hình tiêu chuẩn được cộng đồng khuyến nghị, dựa trên best practices từ tài liệu chính thức của NestJS và các dự án thực tế.
1. Cấu trúc cơ bản khi tạo dự án mới
Khi bạn chạy lệnh nest new project-name, NestJS sẽ tạo ra cấu trúc mặc định như sau:
project-name/
├── src/ # Thư mục nguồn chính (source code)
│ ├── app.controller.spec.ts # Test cho controller
│ ├── app.controller.ts # Controller chính
│ ├── app.module.ts # Module gốc (root module)
│ ├── app.service.ts # Service chính
│ └── main.ts # File khởi động ứng dụng (bootstrap)
├── test/ # Thư mục test (unit và e2e tests)
│ ├── app.e2e-spec.ts
│ └── jest-e2e.json
├── .eslintrc.js # Config ESLint
├── .prettierrc # Config Prettier
├── nest-cli.json # Config Nest CLI
├── package.json # Dependencies và scripts
├── README.md # Tài liệu dự án
├── tsconfig.build.json # Config TypeScript cho build
├── tsconfig.json # Config TypeScript chính
└── yarn.lock / package-lock.json # Lock file dependencies
Đây là cấu trúc đơn giản cho dự án nhỏ. Khi dự án lớn hơn, bạn cần mở rộng nó theo cách modular.
2. Cấu trúc chuẩn hóa cho dự án lớn (Modular Structure)
Để dự án dễ scale, hãy tổ chức theo các module riêng biệt cho từng tính năng (ví dụ: users, auth, products). Mỗi module nên chứa các thành phần liên quan như controllers, services, entities, DTOs, v.v. Dưới đây là ví dụ cấu trúc chuẩn hóa:
project-name/
├── src/ # Thư mục nguồn chính
│ ├── common/ # Các thành phần chung (shared across modules)
│ │ ├── decorators/ # Custom decorators (e.g., roles.decorator.ts)
│ │ ├── filters/ # Exception filters (e.g., http-exception.filter.ts)
│ │ ├── guards/ # Guards (e.g., auth.guard.ts)
│ │ ├── interceptors/ # Interceptors (e.g., logging.interceptor.ts)
│ │ ├── middlewares/ # Middlewares (e.g., logger.middleware.ts)
│ │ ├── pipes/ # Pipes (e.g., validation.pipe.ts)
│ │ └── utils/ # Utilities chung (e.g., helper functions)
│ ├── config/ # Cấu hình ứng dụng (e.g., environment variables)
│ │ └── configuration.ts # ConfigService hoặc file config
│ ├── modules/ # Các module tính năng riêng biệt
│ │ ├── auth/ # Module cho authentication
│ │ │ ├── auth.controller.ts
│ │ │ ├── auth.module.ts
│ │ │ ├── auth.service.ts
│ │ │ ├── dtos/ # Data Transfer Objects (e.g., login.dto.ts)
│ │ │ ├── entities/ # Entities (nếu dùng ORM như TypeORM, e.g., user.entity.ts)
│ │ │ └── interfaces/ # Interfaces (optional)
│ │ ├── users/ # Module cho users management
│ │ │ ├── users.controller.ts
│ │ │ ├── users.module.ts
│ │ │ ├── users.service.ts
│ │ │ ├── dtos/ # e.g., create-user.dto.ts
│ │ │ ├── entities/ # e.g., user.entity.ts
│ │ │ └── tests/ # Tests cho module (optional, có thể để ở thư mục test chung)
│ │ └── ... # Các module khác (e.g., products, orders)
│ ├── shared/ # Các module hoặc service chia sẻ (e.g., database module)
│ │ └── database/ # Ví dụ: database.module.ts (cho TypeORM hoặc Prisma)
│ ├── app.module.ts # Root module, import tất cả modules khác
│ └── main.ts # Bootstrap ứng dụng (NestFactory.create(AppModule))
├── test/ # Thư mục test chung
│ ├── e2e/ # End-to-end tests
│ └── unit/ # Unit tests (có thể tổ chức theo modules)
├── dist/ # Thư mục build (tạo bởi npm run build)
├── .env # Environment variables (không commit vào git)
├── .gitignore # File git ignore
├── nest-cli.json # Config Nest CLI
├── package.json
├── tsconfig.json
└── README.md
Giải thích các thư mục chính:
- src/: Chứa toàn bộ source code. Đây là nơi bạn làm việc chính.
- common/: Các thành phần reusable như guards, pipes, filters. Sử dụng lệnh CLI để tạo (e.g.,
nest g guard common/guards/auth).
- config/: Quản lý cấu hình (sử dụng
@nestjs/config module).
- modules/: Mỗi thư mục con là một module độc lập. Sử dụng
nest g module modules/users để tạo, sau đó thêm controller/service bằng CLI.
- dtos/: Chứa các DTO (Data Transfer Objects) cho validation (thường dùng class-validator).
- entities/: Chứa các entity/model nếu dùng ORM (TypeORM, Mongoose, Prisma).
- interfaces/: Optional, cho các interface/type definitions.
- shared/: Các module chia sẻ, như kết nối database, email service, v.v.
- test/: Tổ chức tests theo unit (jest) và e2e (supertest). Có thể mirror cấu trúc src để dễ quản lý.
- dist/: Tự động tạo khi build, chứa code transpiled sang JS.
3. Best Practices cho Cấu Trúc
- Modular Design: Mỗi module nên tự chứa (self-contained). Import module con vào
app.module.ts hoặc module cha.
- Sử dụng CLI để tạo: Luôn dùng
nest g để tạo file, vì nó tự động import và cấu hình (e.g., nest g resource modules/users sẽ tạo đầy đủ controller, service, module).
- Environment Files: Sử dụng
.env cho variables, và load bằng @nestjs/config.
- Database Integration: Nếu dùng TypeORM/Prisma, đặt trong shared module.
- Testing: Giữ tests gần code (hoặc trong test/ chung). Sử dụng
--no-spec nếu không muốn tạo file test tự động.
- Scalability: Đối với dự án rất lớn, có thể chia modules thành sub-modules (e.g., users/admin, users/public).
- Tools: Sử dụng ESLint/Prettier để giữ code clean. Thêm Husky cho pre-commit hooks.
4. Ví dụ Tạo Cấu Trúc
- Tạo module users:
nest g module modules/users
- Tạo controller:
nest g controller modules/users --no-spec
- Tạo service:
nest g service modules/users --no-spec
- Tạo resource đầy đủ:
nest g resource modules/users (tạo tất cả + DTOs).
Nếu bạn cần ví dụ code cụ thể cho một module nào đó hoặc cách tích hợp database, hãy cho tôi biết thêm chi tiết! Tài liệu chính thức NestJS (docs.nestjs.com) cũng có phần về cấu trúc dự án.