- Enhanced Mermaid diagrams for better visual clarity and consistency across guides. - Added new sections on caching, data consistency, and observability patterns to the architecture documentation. - Improved formatting and structure to align with the English version, ensuring a cohesive user experience. - Removed outdated service communication documentation to reduce clutter and focus on relevant content.
5.7 KiB
5.7 KiB
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:
- 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
-
Clone & Cài đặt dependencies:
pnpm install -
Khởi động infrastructure:
cd deployments/local docker-compose up -d redis -
Thiết lập database:
pnpm prisma migrate dev pnpm prisma db seed -
Khởi động development server:
pnpm dev
Kiến Trúc
Kiến Trúc Phân Lớp
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
- Correlation Middleware: Tạo/truyền correlation và request IDs
- Authentication Middleware: Xác thực JWT tokens
- Validation Middleware: Validate dữ liệu đầu vào với Zod schemas
- Error Handler: Bắt và format lỗi
- Logger Middleware: Ghi log request/response
- 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
{
"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
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ử
# Chạy tất cả tests
pnpm test
# Chạy với coverage
pnpm test:coverage
# Chạy E2E tests
pnpm test:e2e
Docker
# 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
-
Sao chép template:
cp -r services/_template_nodejs services/your-service-name -
Cập nhật tên trong
package.json -
Cấu hình môi trường trong
deployments/local/.env.local -
Cập nhật Prisma schema và chạy migrations
-
Triển khai modules trong
src/modules/ -
Đăng ký trong
deployments/local/docker-compose.yml