Tài liệu này mô tả cấu trúc source base, các công nghệ sử dụng và quy trình khởi tạo dự án.
- Runtime: Node.js
- Language: TypeScript
- Framework: Express.js
- Database ORM: Prisma
- Database: PostgreSQL
- Validation: class-validator, class-transformer
- Authentication: JWT, bcryptjs
- Logging: Winston
Dưới đây là các bước chi tiết đã được thực hiện để xây dựng khung dự án này.
-
Tạo thư mục và khởi tạo Node.js:
mkdir my-new-base cd my-new-base npm init -y -
Cài đặt TypeScript và các công cụ hỗ trợ:
npm install --save-dev typescript ts-node nodemon @types/node
-
Cấu hình TypeScript (
tsconfig.json): Chạy lệnhnpx tsc --initvà cập nhật cấu hình để hỗ trợ Decorators (choclass-validator) và đường dẫn build:{ "compilerOptions": { "target": "es2016", "module": "commonjs", "rootDir": "./src", "outDir": "./dist", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "experimentalDecorators": true, "emitDecoratorMetadata": true } }
-
Express và Middleware (Cors, Helmet, Compression):
npm install express dotenv cors helmet compression npm install --save-dev @types/express @types/cors @types/compression
-
Database (Prisma & PostgreSQL):
npm install @prisma/client pg npm install --save-dev prisma
-
Authentication & Validation: Lưu ý:
reflect-metadatacần được import ở file entry point.npm install bcryptjs jsonwebtoken class-validator class-transformer reflect-metadata npm install --save-dev @types/bcryptjs @types/jsonwebtoken
-
Logging:
npm install winston
Cấu trúc dự án được tổ chức như sau:
.
├── prisma/ # Chứa schema.prisma và migrations
├── src/
│ ├── config/ # Cấu hình môi trường, DB connection
│ ├── common/ # Các thành phần dùng chung (Constants, Enums)
│ │ └── dtos/ # Data Transfer Objects chung
│ ├── helpers/ # Các hàm tiện ích nhỏ
│ ├── middleware/ # Express middlewares (Auth, Error handling)
│ ├── modules/ # Logic nghiệp vụ chính (Controller, Service)
│ ├── routes/ # Định nghĩa API routes
│ ├── utils/ # Các tiện ích lớn (Logger, Response handler)
│ └── validators/ # Custom validators
├── .env # Biến môi trường (Không push lên git)
├── .gitignore
├── package.json
└── tsconfig.json
Bước này không cần tạo file .env và folder prisma, lệnh dưới sẽ tạo giúp bạn
Chạy lệnh sau để khởi tạo Prisma:
npx prisma init --datasource-provider postgresql
Lệnh này sẽ tạo thư mục prisma với file schema.prisma và file .env.
- Clone repository về máy.
- Chạy
npm installđể cài đặt các thư viện. - Copy file
.env.examplethành.envvà điền thông tin Database. - Chạy
npx prisma generateđể tạo Prisma Client. - Bắt đầu code!