- 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.3 KiB
5.3 KiB
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
-
Clone & Install dependencies:
pnpm install -
Start infrastructure:
cd deployments/local docker-compose up -d redis -
Setup database:
pnpm prisma migrate dev pnpm prisma db seed -
Start development server:
pnpm dev
Architecture
Layer Architecture
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
- Correlation Middleware: Generates/propagates correlation and request IDs
- Authentication Middleware: Validates JWT tokens
- Validation Middleware: Validates input data with Zod schemas
- Error Handler: Catches and formats errors
- Logger Middleware: Logs request/response
- 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
{
"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
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
# Run all tests
pnpm test
# Run with coverage
pnpm test:coverage
# Run E2E tests
pnpm test:e2e
Docker
# 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
-
Copy template:
cp -r services/_template_nodejs services/your-service-name -
Update
package.jsonname -
Configure environment in
deployments/local/.env.local -
Update Prisma schema and run migrations
-
Implement your modules in
src/modules/ -
Register in
deployments/local/docker-compose.yml