From 1e22e838796f8dc0824dfa1c945dab2e2b3a1741 Mon Sep 17 00:00:00 2001 From: Ho Ngoc Hai Date: Mon, 12 Jan 2026 12:31:55 +0700 Subject: [PATCH] feat(docs): Streamline Vietnamese documentation with updated diagrams and sections - 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. --- docs/en/templates/dotnet-template.md | 279 +++++++++++++++++++++++++++ docs/en/templates/nodejs-template.md | 214 ++++++++++++++++++++ docs/vi/templates/dotnet-template.md | 279 +++++++++++++++++++++++++++ docs/vi/templates/nodejs-template.md | 214 ++++++++++++++++++++ 4 files changed, 986 insertions(+) create mode 100644 docs/en/templates/dotnet-template.md create mode 100644 docs/en/templates/nodejs-template.md create mode 100644 docs/vi/templates/dotnet-template.md create mode 100644 docs/vi/templates/nodejs-template.md diff --git a/docs/en/templates/dotnet-template.md b/docs/en/templates/dotnet-template.md new file mode 100644 index 00000000..92b617d0 --- /dev/null +++ b/docs/en/templates/dotnet-template.md @@ -0,0 +1,279 @@ +# .NET 10 Microservice Template + +> Enterprise-grade .NET 10 microservice template following DDD, CQRS, and Clean Architecture patterns. + +## Overview + +This template provides a production-ready structure for .NET microservices based on the eShopOnContainers reference architecture with: + +- **Domain-Driven Design (DDD)** - Aggregates, Entities, Value Objects, Domain Events +- **CQRS Pattern** - Separate Commands (write) and Queries (read) with MediatR +- **Clean Architecture** - Domain, Infrastructure, API layered separation +- **EF Core 10** - PostgreSQL with connection resilience +- **FluentValidation** - Request validation +- **API Versioning** - URL segment versioning +- **Health Checks** - Kubernetes-ready probes +- **Structured Logging** - Serilog with console and Seq + +## Prerequisites + +| Requirement | Version | +|-------------|---------| +| .NET SDK | 10.0.101+ | +| Docker | 24.0+ | +| PostgreSQL | 15+ (or use Docker) | + +## Quick Start + +### 1. Create New Service + +```bash +# Copy template to new service +cp -r services/_template_dot_net services/your-service-name +cd services/your-service-name + +# Rename all occurrences of "MyService" to "YourService" +find . -type f -name "*.cs" -exec sed -i '' 's/MyService/YourService/g' {} + +find . -type f -name "*.csproj" -exec sed -i '' 's/MyService/YourService/g' {} + +``` + +### 2. Configure Environment + +```bash +cp .env.example .env +nano .env +``` + +### 3. Run with Docker + +```bash +docker-compose up -d +docker-compose logs -f myservice-api +``` + +### 4. Run Locally + +```bash +dotnet restore +dotnet build +dotnet run --project src/MyService.API +``` + +## Project Structure + +``` +_template_dot_net/ +├── src/ +│ ├── MyService.API/ # Presentation Layer (Controllers, CQRS) +│ │ ├── Controllers/ # API endpoints +│ │ ├── Application/ # CQRS Implementation +│ │ │ ├── Commands/ # Write operations (MediatR) +│ │ │ ├── Queries/ # Read operations +│ │ │ ├── Behaviors/ # MediatR pipeline behaviors +│ │ │ └── Validations/ # FluentValidation validators +│ │ └── Program.cs # Application entry point +│ │ +│ ├── MyService.Domain/ # Domain Layer (Pure business logic) +│ │ ├── AggregatesModel/ # Aggregate roots and entities +│ │ ├── Events/ # Domain events +│ │ ├── Exceptions/ # Domain exceptions +│ │ └── SeedWork/ # Base classes +│ │ +│ └── MyService.Infrastructure/ # Infrastructure Layer +│ ├── EntityConfigurations/ # EF Core configurations +│ ├── Repositories/ # Repository implementations +│ └── MyServiceContext.cs # DbContext with Unit of Work +│ +├── tests/ +│ ├── MyService.UnitTests/ # Unit tests +│ └── MyService.FunctionalTests/ # Integration tests +│ +├── Dockerfile # Multi-stage Docker build +└── docker-compose.yml # Local development setup +``` + +## Architecture + +```mermaid +graph TB + subgraph "API Layer" + C[Controllers] + CMD[Commands] + Q[Queries] + B[Behaviors] + V[Validations] + end + + subgraph "Domain Layer" + AR[Aggregate Roots] + E[Entities] + VO[Value Objects] + DE[Domain Events] + end + + subgraph "Infrastructure Layer" + DB[(PostgreSQL)] + R[Repositories] + CTX[DbContext] + end + + C --> CMD + C --> Q + CMD --> B --> V + CMD --> AR + Q --> R + R --> CTX --> DB + + style C fill:#4a90d9,stroke:#2d5986,color:#fff + style AR fill:#50c878,stroke:#2d8659,color:#fff + style DB fill:#ff6b6b,stroke:#c0392b,color:#fff +``` + +## Layer Responsibilities + +### 1. Domain Layer + +- **ZERO** external dependencies (except MediatR.Contracts) +- Contains only POCO classes +- Implements DDD tactical patterns + +| Component | Purpose | +|-----------|---------| +| **SeedWork** | Base classes: Entity, ValueObject, IAggregateRoot | +| **AggregatesModel** | Aggregate roots with entities and value objects | +| **Events** | Domain events for cross-aggregate communication | +| **Exceptions** | Domain-specific exceptions | + +### 2. Infrastructure Layer + +- Database access (EF Core) +- Repository implementations +- External service integrations + +### 3. API Layer + +- Controllers for HTTP handling +- Commands for write operations +- Queries for read operations +- MediatR behaviors for cross-cutting concerns + +## CQRS Pattern + +### Commands (Write Operations) + +```csharp +public record CreateSampleCommand(string Name, string? Description) + : IRequest; + +public class CreateSampleCommandHandler : IRequestHandler +{ + public async Task Handle(CreateSampleCommand request, CancellationToken ct) + { + var sample = new Sample(request.Name, request.Description); + _repository.Add(sample); + await _repository.UnitOfWork.SaveEntitiesAsync(ct); + return new CreateSampleCommandResult(sample.Id); + } +} +``` + +### MediatR Pipeline + +``` +Request → LoggingBehavior → ValidatorBehavior → TransactionBehavior → Handler → Response +``` + +## API Endpoints + +| Method | Endpoint | Description | +|--------|----------|-------------| +| `GET` | `/api/v1/samples` | Get all samples | +| `GET` | `/api/v1/samples/{id}` | Get sample by ID | +| `POST` | `/api/v1/samples` | Create new sample | +| `PUT` | `/api/v1/samples/{id}` | Update sample | +| `DELETE` | `/api/v1/samples/{id}` | Delete sample | +| `PATCH` | `/api/v1/samples/{id}/status` | Change status | + +### Health Endpoints + +| Endpoint | Purpose | +|----------|---------| +| `/health` | Full health status | +| `/health/live` | Liveness probe | +| `/health/ready` | Readiness probe | + +## Environment Variables + +| Variable | Description | Default | +|----------|-------------|---------| +| `ASPNETCORE_ENVIRONMENT` | Environment name | `Development` | +| `DATABASE_URL` | PostgreSQL connection | - | +| `REDIS_URL` | Redis connection | - | +| `JWT_SECRET` | JWT signing secret | - | + +## Testing + +```bash +# Run all tests +dotnet test + +# Run with coverage +dotnet test /p:CollectCoverage=true /p:CoverageReportFormat=cobertura + +# Run specific test project +dotnet test tests/MyService.UnitTests +``` + +## Deployment + +### Docker Build + +```bash +docker build -t myservice:latest . +docker run -p 5000:8080 --env-file .env myservice:latest +``` + +### Kubernetes + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: myservice-api +spec: + replicas: 3 + template: + spec: + containers: + - name: api + image: myservice:latest + livenessProbe: + httpGet: + path: /health/live + port: 8080 + readinessProbe: + httpGet: + path: /health/ready + port: 8080 +``` + +## What's New in .NET 10 + +- **C# 14** language features +- Improved **Native AOT** support +- Better **async/await** performance +- Enhanced **JSON serialization** +- 3-year **LTS** support (until November 2028) + +## Related Documentation + +- [Architecture Details](../architecture/microservices-communication.md) +- [DDD Patterns](../architecture/system-design.md) +- [Deployment Guide](../guides/deployment.md) + +## Resources + +- [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers) +- [.NET 10 Documentation](https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-10) +- [MediatR](https://github.com/jbogard/MediatR) +- [FluentValidation](https://docs.fluentvalidation.net/) diff --git a/docs/en/templates/nodejs-template.md b/docs/en/templates/nodejs-template.md new file mode 100644 index 00000000..4b5c8287 --- /dev/null +++ b/docs/en/templates/nodejs-template.md @@ -0,0 +1,214 @@ +# Node.js Microservice Template + +> Standard template for creating new microservices in the @goodgo ecosystem using Node.js/TypeScript. + +## Overview + +This template provides a complete, production-ready foundation for building individual microservices with: + +- **Framework**: Express.js with TypeScript +- **Database**: Prisma ORM with PostgreSQL +- **Validation**: Zod for environment & input validation +- **Observability**: Prometheus metrics, structured logging, OpenTelemetry/Jaeger tracing +- **Resilience**: Graceful shutdown, rate limiting (Redis), circuit breaker, health checks +- **Caching**: Redis caching strategy +- **Security**: Helmet & CORS configured + +## Project Structure + +``` +src/ +├── config/ # Configuration & Env validation +├── middlewares/ # Express middlewares (error, logger, metrics) +├── modules/ # Feature modules (controller, service, repository) +├── routes/ # API route definitions +└── main.ts # Entry point & App bootstrapping +``` + +## Getting Started + +### Prerequisites + +- Node.js >= 20 +- pnpm +- Docker (Redis required) + +### Installation + +1. **Clone & Install dependencies**: + ```bash + pnpm install + ``` + +2. **Start infrastructure**: + ```bash + cd deployments/local + docker-compose up -d redis + ``` + +3. **Setup database**: + ```bash + pnpm prisma migrate dev + pnpm prisma db seed + ``` + +4. **Start development server**: + ```bash + pnpm dev + ``` + +## Architecture + +### Layer Architecture + +```mermaid +graph TD + Request[HTTP Request] --> Middleware[Middleware Chain] + + subgraph SingleService[Single Service Boundary] + 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 +``` + +### Middleware Chain + +1. **Correlation Middleware**: Generates/propagates correlation and request IDs +2. **Authentication Middleware**: Validates JWT tokens +3. **Validation Middleware**: Validates input data with Zod schemas +4. **Error Handler**: Catches and formats errors +5. **Logger Middleware**: Logs request/response +6. **Metrics Middleware**: Collects Prometheus metrics + +### Controller → Service → Repository Pattern + +- **Controller**: Handles HTTP requests, orchestrates services +- **Service**: Contains business logic, independent of HTTP +- **Repository**: Abstracts database operations with Prisma + +## API Endpoints + +### Health Endpoints + +| Endpoint | Purpose | +|----------|---------| +| `/health` | Full health status | +| `/health/live` | Liveness probe | +| `/health/ready` | Readiness probe | + +### Feature Management + +| Method | Endpoint | Description | +|--------|----------|-------------| +| `GET` | `/api/v1/features` | Get all features | +| `GET` | `/api/v1/features/{id}` | Get feature by ID | +| `POST` | `/api/v1/features` | Create feature (admin) | +| `PUT` | `/api/v1/features/{id}` | Update feature | +| `DELETE` | `/api/v1/features/{id}` | Delete feature | +| `PATCH` | `/api/v1/features/{id}/toggle` | Toggle status | + +## Response Format + +```json +{ + "success": true, + "data": { ... }, + "message": "Operation completed", + "timestamp": "2024-01-01T00:00:00.000Z" +} +``` + +## Environment Variables + +| Variable | Description | Required | +|----------|-------------|----------| +| `PORT` | Server port | No (default: 5000) | +| `DATABASE_URL` | PostgreSQL connection | **Yes** | +| `REDIS_URL` | Redis connection | No | +| `JWT_SECRET` | JWT secret key | **Yes** | +| `TRACING_ENABLED` | Enable Jaeger tracing | No | + +## Platform Integration + +### Add to 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" +``` + +### Access Points + +- **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 + +## Testing + +```bash +# Run all tests +pnpm test + +# Run with coverage +pnpm test:coverage + +# Run E2E tests +pnpm test:e2e +``` + +## Docker + +```bash +# Build image +docker build -t your-service:latest . + +# Run container +docker run -p 5000:5000 --env-file .env your-service:latest +``` + +## Creating a New Service + +1. Copy template: + ```bash + cp -r services/_template_nodejs services/your-service-name + ``` + +2. Update `package.json` name + +3. Configure environment in `deployments/local/.env.local` + +4. Update Prisma schema and run migrations + +5. Implement your modules in `src/modules/` + +6. Register in `deployments/local/docker-compose.yml` + +## Related Documentation + +- [Architecture Details](../architecture/microservices-communication.md) +- [API Design Standards](../guides/api-design.md) +- [Testing Patterns](../guides/testing.md) diff --git a/docs/vi/templates/dotnet-template.md b/docs/vi/templates/dotnet-template.md new file mode 100644 index 00000000..a361d163 --- /dev/null +++ b/docs/vi/templates/dotnet-template.md @@ -0,0 +1,279 @@ +# Template Microservice .NET 10 + +> Template microservice .NET 10 cấp doanh nghiệp theo các pattern DDD, CQRS và Clean Architecture. + +## Tổng Quan + +Template này cung cấp cấu trúc sẵn sàng production cho microservices .NET dựa trên kiến trúc tham chiếu eShopOnContainers với: + +- **Domain-Driven Design (DDD)** - Aggregates, Entities, Value Objects, Domain Events +- **CQRS Pattern** - Tách biệt Commands (ghi) và Queries (đọc) với MediatR +- **Clean Architecture** - Phân tầng Domain, Infrastructure, API +- **EF Core 10** - PostgreSQL với connection resilience +- **FluentValidation** - Validation request +- **API Versioning** - Versioning theo URL segment +- **Health Checks** - Probes sẵn sàng cho Kubernetes +- **Structured Logging** - Serilog với console và Seq + +## Yêu Cầu + +| Yêu cầu | Phiên bản | +|---------|-----------| +| .NET SDK | 10.0.101+ | +| Docker | 24.0+ | +| PostgreSQL | 15+ (hoặc dùng Docker) | + +## Bắt Đầu Nhanh + +### 1. Tạo Service Mới + +```bash +# Sao chép template sang service mới +cp -r services/_template_dot_net services/your-service-name +cd services/your-service-name + +# Đổi tên tất cả "MyService" thành "YourService" +find . -type f -name "*.cs" -exec sed -i '' 's/MyService/YourService/g' {} + +find . -type f -name "*.csproj" -exec sed -i '' 's/MyService/YourService/g' {} + +``` + +### 2. Cấu Hình Môi Trường + +```bash +cp .env.example .env +nano .env +``` + +### 3. Chạy với Docker + +```bash +docker-compose up -d +docker-compose logs -f myservice-api +``` + +### 4. Chạy Local + +```bash +dotnet restore +dotnet build +dotnet run --project src/MyService.API +``` + +## Cấu Trúc Dự Án + +``` +_template_dot_net/ +├── src/ +│ ├── MyService.API/ # Lớp Presentation (Controllers, CQRS) +│ │ ├── Controllers/ # Các API endpoints +│ │ ├── Application/ # Triển khai CQRS +│ │ │ ├── Commands/ # Thao tác ghi (MediatR) +│ │ │ ├── Queries/ # Thao tác đọc +│ │ │ ├── Behaviors/ # MediatR pipeline behaviors +│ │ │ └── Validations/ # FluentValidation validators +│ │ └── Program.cs # Điểm vào ứng dụng +│ │ +│ ├── MyService.Domain/ # Lớp Domain (Business logic thuần túy) +│ │ ├── AggregatesModel/ # Aggregate roots và entities +│ │ ├── Events/ # Domain events +│ │ ├── Exceptions/ # Domain exceptions +│ │ └── SeedWork/ # Base classes +│ │ +│ └── MyService.Infrastructure/ # Lớp Infrastructure +│ ├── EntityConfigurations/ # Cấu hình EF Core +│ ├── Repositories/ # Triển khai repositories +│ └── MyServiceContext.cs # DbContext với Unit of Work +│ +├── tests/ +│ ├── MyService.UnitTests/ # Unit tests +│ └── MyService.FunctionalTests/ # Integration tests +│ +├── Dockerfile # Multi-stage Docker build +└── docker-compose.yml # Thiết lập phát triển local +``` + +## Kiến Trúc + +```mermaid +graph TB + subgraph "Lớp API" + C[Controllers] + CMD[Commands] + Q[Queries] + B[Behaviors] + V[Validations] + end + + subgraph "Lớp Domain" + AR[Aggregate Roots] + E[Entities] + VO[Value Objects] + DE[Domain Events] + end + + subgraph "Lớp Infrastructure" + DB[(PostgreSQL)] + R[Repositories] + CTX[DbContext] + end + + C --> CMD + C --> Q + CMD --> B --> V + CMD --> AR + Q --> R + R --> CTX --> DB + + style C fill:#4a90d9,stroke:#2d5986,color:#fff + style AR fill:#50c878,stroke:#2d8659,color:#fff + style DB fill:#ff6b6b,stroke:#c0392b,color:#fff +``` + +## Trách Nhiệm Các Lớp + +### 1. Lớp Domain + +- **ZERO** phụ thuộc bên ngoài (ngoại trừ MediatR.Contracts) +- Chỉ chứa các class POCO +- Triển khai các tactical patterns của DDD + +| Thành phần | Mục Đích | +|------------|----------| +| **SeedWork** | Base classes: Entity, ValueObject, IAggregateRoot | +| **AggregatesModel** | Aggregate roots với entities và value objects | +| **Events** | Domain events cho giao tiếp cross-aggregate | +| **Exceptions** | Domain exceptions | + +### 2. Lớp Infrastructure + +- Truy cập database (EF Core) +- Triển khai repositories +- Tích hợp external services + +### 3. Lớp API + +- Controllers để xử lý HTTP +- Commands cho các thao tác ghi +- Queries cho các thao tác đọc +- MediatR behaviors cho cross-cutting concerns + +## Pattern CQRS + +### Commands (Thao Tác Ghi) + +```csharp +public record CreateSampleCommand(string Name, string? Description) + : IRequest; + +public class CreateSampleCommandHandler : IRequestHandler +{ + public async Task Handle(CreateSampleCommand request, CancellationToken ct) + { + var sample = new Sample(request.Name, request.Description); + _repository.Add(sample); + await _repository.UnitOfWork.SaveEntitiesAsync(ct); + return new CreateSampleCommandResult(sample.Id); + } +} +``` + +### Pipeline MediatR + +``` +Request → LoggingBehavior → ValidatorBehavior → TransactionBehavior → Handler → Response +``` + +## Các API Endpoints + +| Method | Endpoint | Mô Tả | +|--------|----------|-------| +| `GET` | `/api/v1/samples` | Lấy tất cả samples | +| `GET` | `/api/v1/samples/{id}` | Lấy sample theo ID | +| `POST` | `/api/v1/samples` | Tạo sample mới | +| `PUT` | `/api/v1/samples/{id}` | Cập nhật sample | +| `DELETE` | `/api/v1/samples/{id}` | Xóa sample | +| `PATCH` | `/api/v1/samples/{id}/status` | Thay đổi trạng thái | + +### 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 | + +## Biến Môi Trường + +| Biến | Mô Tả | Mặc định | +|------|-------|----------| +| `ASPNETCORE_ENVIRONMENT` | Tên môi trường | `Development` | +| `DATABASE_URL` | Kết nối PostgreSQL | - | +| `REDIS_URL` | Kết nối Redis | - | +| `JWT_SECRET` | Secret ký JWT | - | + +## Kiểm Thử + +```bash +# Chạy tất cả tests +dotnet test + +# Chạy với coverage +dotnet test /p:CollectCoverage=true /p:CoverageReportFormat=cobertura + +# Chạy project test cụ thể +dotnet test tests/MyService.UnitTests +``` + +## Triển Khai + +### Docker Build + +```bash +docker build -t myservice:latest . +docker run -p 5000:8080 --env-file .env myservice:latest +``` + +### Kubernetes + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: myservice-api +spec: + replicas: 3 + template: + spec: + containers: + - name: api + image: myservice:latest + livenessProbe: + httpGet: + path: /health/live + port: 8080 + readinessProbe: + httpGet: + path: /health/ready + port: 8080 +``` + +## Có Gì Mới Trong .NET 10 + +- Tính năng ngôn ngữ **C# 14** +- Hỗ trợ **Native AOT** được cải thiện +- Hiệu suất **async/await** tốt hơn +- **JSON serialization** được nâng cao +- Hỗ trợ **LTS** 3 năm (đến tháng 11/2028) + +## Tài Liệu Liên Quan + +- [Chi Tiết Kiến Trúc](../architecture/microservices-communication.md) +- [DDD Patterns](../architecture/system-design.md) +- [Hướng Dẫn Triển Khai](../guides/deployment.md) + +## Tài Nguyên + +- [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers) +- [Tài liệu .NET 10](https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-10) +- [MediatR](https://github.com/jbogard/MediatR) +- [FluentValidation](https://docs.fluentvalidation.net/) diff --git a/docs/vi/templates/nodejs-template.md b/docs/vi/templates/nodejs-template.md new file mode 100644 index 00000000..072281f4 --- /dev/null +++ b/docs/vi/templates/nodejs-template.md @@ -0,0 +1,214 @@ +# 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 + +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)