Files
pos-system/docs/en/templates/nodejs-template.md
Ho Ngoc Hai 1e22e83879 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.
2026-01-12 12:31:55 +07:00

215 lines
5.3 KiB
Markdown

# 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)