236 lines
6.4 KiB
Markdown
236 lines
6.4 KiB
Markdown
# Template Architecture Analysis
|
|
|
|
## Overview / Tổng quan
|
|
|
|
**Service**: `_template` - Standard Microservice Template
|
|
**TypeScript Files**: 38 files
|
|
**Last Updated**: Dec 27, 2024
|
|
|
|
## Module Structure / Cấu trúc Module
|
|
|
|
### Core Modules (4 modules)
|
|
|
|
```
|
|
src/modules/
|
|
├── common/ # Shared utilities, base classes
|
|
├── feature/ # Example feature module (for demonstration)
|
|
├── health/ # Health check endpoints
|
|
└── metrics/ # Prometheus metrics
|
|
```
|
|
|
|
### Module Breakdown
|
|
|
|
#### 1. Common Module
|
|
**Purpose**: Shared utilities and base classes for all modules
|
|
**Key Files**:
|
|
- `repository.ts` - Base repository pattern with Prisma
|
|
- `types.ts` - Shared TypeScript types
|
|
|
|
#### 2. Feature Module (Example)
|
|
**Purpose**: Demonstrates standard module structure
|
|
**Key Files**:
|
|
- `feature.controller.ts` - Express route handlers
|
|
- `feature.service.ts` - Business logic layer
|
|
- `feature.repository.ts` - Data access via Prisma
|
|
- `feature.dto.ts` - Zod validation schemas
|
|
- `feature.module.ts` - Module wiring and router export
|
|
- `__tests__/` - Unit and E2E tests
|
|
|
|
**Pattern**:
|
|
```
|
|
Controller → Service → Repository → Prisma → PostgreSQL
|
|
```
|
|
|
|
#### 3. Health Module
|
|
**Purpose**: Kubernetes liveness/readiness probes
|
|
**Endpoints**:
|
|
- `GET /health` - Overall health check
|
|
- `GET /health/live` - Liveness probe (is process running?)
|
|
- `GET /health/ready` - Readiness probe (can serve traffic?)
|
|
|
|
#### 4. Metrics Module
|
|
**Purpose**: Prometheus metrics exposure
|
|
**Endpoint**:
|
|
- `GET /metrics` - Prometheus format metrics
|
|
**Metrics**:
|
|
- HTTP request duration (histogram)
|
|
- HTTP request count (counter)
|
|
- Active requests (gauge)
|
|
- Error count (counter)
|
|
|
|
## Middleware Stack / Stack Middleware
|
|
|
|
```typescript
|
|
// Execution Order (from main.ts)
|
|
1. Correlation ID Middleware // Generate/propagate correlation IDs
|
|
2. Request Logger Middleware // Log incoming requests
|
|
3. Metrics Middleware // Track request metrics
|
|
4. Error Handler Middleware // Global error handling (LAST)
|
|
```
|
|
|
|
**Key Middlewares**:
|
|
- `correlation.middleware.ts` - Request tracing with x-correlation-id
|
|
- `logger.middleware.ts` - Structured logging with Winston
|
|
- `metrics.middleware.ts` - Prometheus instrumentation
|
|
- `error.middleware.ts` - Centralized error handling
|
|
|
|
## Configuration / Cấu hình
|
|
|
|
**Config Files** (with Zod validation):
|
|
- `app.config.ts` - App-level config (PORT, NODE_ENV, API_VERSION)
|
|
- `database.config.ts` - Prisma database configuration
|
|
- `redis.config.ts` - Redis cache configuration
|
|
|
|
**Environment Variables**:
|
|
| Variable | Required | Description |
|
|
|----------|----------|-------------|
|
|
| `PORT` | No | Server port (default: 5000) |
|
|
| `NODE_ENV` | No | Environment (default: development) |
|
|
| `DATABASE_URL` | **Yes** | PostgreSQL connection string |
|
|
| `REDIS_URL` | No | Redis connection (default: redis://localhost:6379) |
|
|
| `SERVICE_NAME` | No | Service identifier |
|
|
| `API_VERSION` | No | API version (default: v1) |
|
|
|
|
## Database Layer / Tầng Database
|
|
|
|
**ORM**: Prisma
|
|
**Database**: PostgreSQL
|
|
**Pattern**: Repository Pattern with Base Repository
|
|
|
|
**Example Model** (from prisma/schema.prisma):
|
|
```prisma
|
|
model Feature {
|
|
id String @id @default(cuid())
|
|
name String @unique
|
|
description String?
|
|
enabled Boolean @default(true)
|
|
config Json?
|
|
tags String[]
|
|
createdAt DateTime @default(now())
|
|
updatedAt DateTime @updatedAt
|
|
|
|
@@map("features")
|
|
}
|
|
```
|
|
|
|
## API Routes / Routes API
|
|
|
|
**Base Path**: `/api/v1`
|
|
|
|
**Routing Strategy**:
|
|
```typescript
|
|
// src/routes/index.ts
|
|
/api/v1
|
|
├── /features → Feature Module
|
|
├── /health → Health Module
|
|
└── /metrics → Metrics Module
|
|
```
|
|
|
|
## Testing Strategy / Chiến lược Testing
|
|
|
|
**Test Structure**:
|
|
```
|
|
src/
|
|
├── modules/
|
|
│ └── feature/
|
|
│ └── __tests__/
|
|
│ ├── feature.service.test.ts # Unit tests
|
|
│ └── feature.e2e.test.ts # E2E tests
|
|
└── __tests__/
|
|
└── setupTests.ts # Test configuration
|
|
```
|
|
|
|
**Testing Stack**:
|
|
- **Framework**: Jest
|
|
- **E2E**: Supertest
|
|
- **Coverage**: 70%+ requirement
|
|
|
|
## Observability / Khả năng quan sát
|
|
|
|
### Logging
|
|
- **Library**: Winston
|
|
- **Format**: Structured JSON
|
|
- **Levels**: error, warn, info, debug
|
|
- **Context**: Correlation IDs in every log
|
|
|
|
### Metrics
|
|
- **Library**: prom-client (Prometheus)
|
|
- **Endpoint**: `/metrics`
|
|
- **Types**: Counter, Gauge, Histogram
|
|
|
|
### Tracing
|
|
- **Library**: OpenTelemetry (planned)
|
|
- **Backend**: Jaeger (optional)
|
|
- **Env Var**: `TRACING_ENABLED`
|
|
|
|
## Docker Support / Hỗ trợ Docker
|
|
|
|
**Dockerfile Features**:
|
|
- Multi-stage build (builder → runner)
|
|
- Non-root user (node:node)
|
|
- Production dependencies only
|
|
- Health check support
|
|
|
|
**Image Size**: ~200MB (optimized)
|
|
|
|
## Key Patterns Demonstrated / Patterns Chính
|
|
|
|
1. **Controller-Service-Repository Pattern**
|
|
- Clear separation of concerns
|
|
- Testable layers
|
|
|
|
2. **Dependency Injection via Constructor**
|
|
- Easy mocking for tests
|
|
- Clear dependencies
|
|
|
|
3. **Zod Validation**
|
|
- Runtime type safety
|
|
- Environment validation
|
|
|
|
4. **Error Handling**
|
|
- Custom error classes
|
|
- Global error middleware
|
|
|
|
5. **Correlation IDs**
|
|
- Request tracing
|
|
- Distributed debugging
|
|
|
|
## Security Features / Tính năng Bảo mật
|
|
|
|
- **Helmet**: HTTP security headers
|
|
- **CORS**: Configurable CORS
|
|
- **Input Validation**: Zod schemas
|
|
- **SQL Injection Prevention**: Prisma ORM (parameterized queries)
|
|
|
|
## Deployment Ready / Sẵn sàng Deploy
|
|
|
|
- ✅ Dockerfile with multi-stage build
|
|
- ✅ Health check endpoints (K8s compatible)
|
|
- ✅ Prometheus metrics
|
|
- ✅ Structured logging
|
|
- ✅ Graceful shutdown
|
|
- ✅ Connection pooling (Prisma)
|
|
|
|
## Gaps / Điểm còn thiếu
|
|
|
|
Compared to full production service (iam-service):
|
|
- ❌ No caching layer (no Redis integration shown)
|
|
- ❌ No authentication middleware
|
|
- ❌ No rate limiting
|
|
- ❌ No circuit breaker pattern
|
|
- ❌ No event sourcing
|
|
- ❌ No advanced RBAC
|
|
|
|
**Note**: These are intentionally omitted to keep template simple. They are demonstrated in `iam-service`.
|
|
|
|
## Summary / Tóm tắt
|
|
|
|
`_template` is a **minimal, production-ready microservice template** that demonstrates:
|
|
- Clean architecture (Controller-Service-Repository)
|
|
- TypeScript best practices
|
|
- Testing setup
|
|
- Basic observability (logging, metrics, health checks)
|
|
- Docker deployment
|
|
|
|
It serves as a **starting point** for new services, with `iam-service` showing how to expand into a full production service with advanced features.
|