Files
pos-system/docs/vi/templates/nodejs-template.md
Ho Ngoc Hai 02e1053eb5 docs: Update architecture and template documentation for GoodGo Platform
- Revised the architecture documentation to include detailed diagrams and descriptions for the GoodGo Microservices Platform, enhancing clarity on system components and interactions.
- Updated the .NET template documentation to reflect new naming conventions and project structures, ensuring consistency across services.
- Added real-world examples and practical setup instructions for local development, including Traefik routing and environment variable configurations.
- Enhanced the guide documentation with verification checklists and troubleshooting steps to support developers in deploying and managing services effectively.
2026-01-14 12:21:51 +07:00

217 lines
5.9 KiB
Markdown

# Template Microservice Node.js
> Template chuẩn để tạo các microservice mới trong hệ sinh thái @goodgo sử dụng Node.js/TypeScript.
## Tổng Quan
Template này cung cấp nền tảng hoàn chỉnh, sẵn sàng production để xây dựng các microservice với:
> **Lưu ý**: Template này dành cho tương lai. Hiện tại dự án GoodGo chủ yếu sử dụng .NET services. Xem [dotnet-template.md](./dotnet-template.md) cho template đang sử dụng.
- **Framework**: Express.js với TypeScript
- **Database**: Prisma ORM với PostgreSQL
- **Validation**: Zod cho validation biến môi trường và đầu vào
- **Observability**: Prometheus metrics, logging có cấu trúc, tích hợp OpenTelemetry/Jaeger
- **Resilience**: Graceful shutdown, rate limiting (Redis), circuit breaker, health checks
- **Caching**: Chiến lược caching với Redis
- **Security**: Đã cấu hình Helmet & CORS
## Cấu Trúc Dự Án
```
src/
├── config/ # Cấu hình & Validate biến môi trường
├── middlewares/ # Express middlewares (error, logger, metrics)
├── modules/ # Feature modules (controller, service, repository)
├── routes/ # Định nghĩa API routes
└── main.ts # Entry point & App bootstrapping
```
## Bắt Đầu
### Yêu Cầu
- Node.js >= 20
- pnpm
- Docker (yêu cầu Redis)
### Cài Đặt
1. **Clone & Cài đặt dependencies**:
```bash
pnpm install
```
2. **Khởi động infrastructure**:
```bash
cd deployments/local
docker-compose up -d redis
```
3. **Thiết lập database**:
```bash
pnpm prisma migrate dev
pnpm prisma db seed
```
4. **Khởi động development server**:
```bash
pnpm dev
```
## Kiến Trúc
### Kiến Trúc Phân Lớp
```mermaid
graph TD
Request[HTTP Request] --> Middleware[Middleware Chain]
subgraph SingleService[Ranh Giới Service]
Middleware --> Correlation[Correlation ID]
Correlation --> Auth[Authentication]
Auth --> Validation[Validation]
Validation --> Error[Error Handler]
Error --> Logger[Request Logger]
Logger --> Metrics[Metrics Collector]
Metrics --> Router[Router Layer]
Router --> Controller[Controller Layer]
Controller --> Service[Service Layer]
Service --> Repository[Repository Layer]
Repository --> Database[(PostgreSQL)]
Service --> Cache[(Redis)]
end
style Correlation fill:#e1f5fe
style Auth fill:#f3e5f5
style Validation fill:#e8f5e8
```
### Chuỗi Middleware
1. **Correlation Middleware**: Tạo/truyền correlation và request IDs
2. **Authentication Middleware**: Xác thực JWT tokens
3. **Validation Middleware**: Validate dữ liệu đầu vào với Zod schemas
4. **Error Handler**: Bắt và format lỗi
5. **Logger Middleware**: Ghi log request/response
6. **Metrics Middleware**: Thu thập Prometheus metrics
### Pattern Controller → Service → Repository
- **Controller**: Xử lý HTTP requests, điều phối services
- **Service**: Chứa business logic, độc lập với HTTP
- **Repository**: Trừu tượng hóa thao tác database với Prisma
## Các API Endpoints
### Health Endpoints
| Endpoint | Mục Đích |
|----------|----------|
| `/health` | Trạng thái health đầy đủ |
| `/health/live` | Kiểm tra sống |
| `/health/ready` | Kiểm tra sẵn sàng |
### Quản Lý Feature
| Method | Endpoint | Mô Tả |
|--------|----------|-------|
| `GET` | `/api/v1/features` | Lấy tất cả features |
| `GET` | `/api/v1/features/{id}` | Lấy feature theo ID |
| `POST` | `/api/v1/features` | Tạo feature (admin) |
| `PUT` | `/api/v1/features/{id}` | Cập nhật feature |
| `DELETE` | `/api/v1/features/{id}` | Xóa feature |
| `PATCH` | `/api/v1/features/{id}/toggle` | Chuyển đổi trạng thái |
## Định Dạng Response
```json
{
"success": true,
"data": { ... },
"message": "Hoạt động hoàn thành",
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
## Biến Môi Trường
| Biến | Mô Tả | Bắt buộc |
|------|-------|----------|
| `PORT` | Cổng server | Không (mặc định: 5000) |
| `DATABASE_URL` | Kết nối PostgreSQL | **Có** |
| `REDIS_URL` | Kết nối Redis | Không |
| `JWT_SECRET` | Khóa bí mật JWT | **Có** |
| `TRACING_ENABLED` | Bật Jaeger tracing | Không |
## Tích Hợp Nền Tảng
### Thêm vào docker-compose.yml
```yaml
services:
your-service:
build:
context: ../..
dockerfile: services/your-service/Dockerfile
labels:
- "traefik.enable=true"
- "traefik.http.routers.your-service.rule=PathPrefix(`/api/v1/your-service`)"
- "traefik.http.services.your-service.loadbalancer.server.port=5002"
```
### Điểm Truy Cập
- **API**: http://localhost/api/v1/your-service
- **Health**: http://localhost/api/v1/your-service/health
- **API Docs**: http://localhost/api/v1/your-service/api-docs
- **Traefik Dashboard**: http://localhost:8080
## Kiểm Thử
```bash
# Chạy tất cả tests
pnpm test
# Chạy với coverage
pnpm test:coverage
# Chạy E2E tests
pnpm test:e2e
```
## Docker
```bash
# Build image
docker build -t your-service:latest .
# Chạy container
docker run -p 5000:5000 --env-file .env your-service:latest
```
## Tạo Service Mới
1. Sao chép template:
```bash
cp -r services/_template_nodejs services/your-service-name
```
2. Cập nhật tên trong `package.json`
3. Cấu hình môi trường trong `deployments/local/.env.local`
4. Cập nhật Prisma schema và chạy migrations
5. Triển khai modules trong `src/modules/`
6. Đăng ký trong `deployments/local/docker-compose.yml`
## Tài Liệu Liên Quan
- [Chi Tiết Kiến Trúc](../architecture/microservices-communication.md)
- [Tiêu Chuẩn Thiết Kế API](../guides/api-design.md)
- [Patterns Kiểm Thử](../guides/testing.md)