6.4 KiB
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 Prismatypes.ts- Shared TypeScript types
2. Feature Module (Example)
Purpose: Demonstrates standard module structure Key Files:
feature.controller.ts- Express route handlersfeature.service.ts- Business logic layerfeature.repository.ts- Data access via Prismafeature.dto.ts- Zod validation schemasfeature.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 checkGET /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
// 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-idlogger.middleware.ts- Structured logging with Winstonmetrics.middleware.ts- Prometheus instrumentationerror.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 configurationredis.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):
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:
// 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
-
Controller-Service-Repository Pattern
- Clear separation of concerns
- Testable layers
-
Dependency Injection via Constructor
- Easy mocking for tests
- Clear dependencies
-
Zod Validation
- Runtime type safety
- Environment validation
-
Error Handling
- Custom error classes
- Global error middleware
-
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.