{"id":30708509,"url":"https://github.com/andreibesleaga/nestjs-mstv","last_synced_at":"2026-04-27T16:32:48.123Z","repository":{"id":309271175,"uuid":"1035656721","full_name":"andreibesleaga/nestjs-mstv","owner":"andreibesleaga","description":"NestJs/Node.js backend template, multi-protocol and microservice design patterns support.","archived":false,"fork":false,"pushed_at":"2026-03-27T07:13:08.000Z","size":2393,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-03-27T16:48:49.430Z","etag":null,"topics":["backend","fastify","microservice","nestjs","nestjs-backend","nestjs-boilerplate","nodejs","template"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/andreibesleaga.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-08-10T21:29:37.000Z","updated_at":"2026-03-27T07:13:06.000Z","dependencies_parsed_at":"2025-08-15T11:35:09.213Z","dependency_job_id":null,"html_url":"https://github.com/andreibesleaga/nestjs-mstv","commit_stats":null,"previous_names":["andreibesleaga/nestjs-template-variant","andreibesleaga/nestjs-mstv"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/andreibesleaga/nestjs-mstv","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreibesleaga%2Fnestjs-mstv","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreibesleaga%2Fnestjs-mstv/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreibesleaga%2Fnestjs-mstv/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreibesleaga%2Fnestjs-mstv/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/andreibesleaga","download_url":"https://codeload.github.com/andreibesleaga/nestjs-mstv/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreibesleaga%2Fnestjs-mstv/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32345803,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-26T23:26:28.701Z","status":"online","status_checked_at":"2026-04-27T02:00:06.769Z","response_time":128,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["backend","fastify","microservice","nestjs","nestjs-backend","nestjs-boilerplate","nodejs","template"],"created_at":"2025-09-02T22:01:49.712Z","updated_at":"2026-04-27T16:32:48.116Z","avatar_url":"https://github.com/andreibesleaga.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Microservice Template Variant\n\nA clean, extensible, maintainable, Node.js based, NestJs extended, microservice template implementing essential microservice design patterns with optional advanced features. Designed for rapid development with production-ready defaults, for single microservice development and multi microservices design architectures.\n\nYou can view the [ARCHITECTURE.md](ARCHITECTURE.md) file for more details.\n\nSimple by default, scalable by choice. Enable only what you need.\n\n## ⚡ **Core Features**\n\n- **�️ Feature Flags System** - Flags to enable/disable services as needed\n- **🚀 Fast Startup** - Lightweight by default, everything optional\n- **� Modular Design** - Focused managers for transport, streaming, scheduling, caching\n- **🔧 Type Safety** - Comprehensive TypeScript interfaces eliminate runtime errors\n- **🚀 Fast Startup** - Minimal resource usage with selective service loading\n- **📊 Performance Monitoring** - Optional performance interceptors and metrics\n- **🔧 Environment-Specific Configs** - Different feature sets for dev/test/prod\n\n## 🏗️ **Architecture**\n\n- **Clean Services** - Single responsibility focused managers\n- **Protocol Support** - HTTP/REST, GraphQL, WebSocket, MQTT (gRPC optional)\n- **Microservice Ready** - Optional TCP, Redis, NATS, RabbitMQ transports\n- **Configuration Diet** - Essential configs only, no complexity bloat\n- **SOLID Principles** - Maintainable and extensible codebase with basic DDD concept\n- **Event-Driven Architecture** - Kafka integration for scalable messaging\n\n## 🗄️ **Database \u0026 Persistence**\n\n- **Database Support** - PostgreSQL (via Prisma) or MongoDB with runtime selection\n- **Simple Repository Pattern** - Clean data access abstraction\n- **Connection Management** - Health checks and proper connection handling\n- **Database Migrations** - Prisma/MongoDB migrations and seed scripts\n- **Connection Management** - Proper connection pooling and health checks\n\n## 🔐 **Authentication \u0026 Security**\n\n- **JWT Authentication** - Access and refresh tokens\n- **CASL Authorization** - Role-based access control\n- **Password Security** - bcrypt hashing\n- **Security Headers** - Helmet, CORS, rate limiting\n- **Input Validation** - class-validator integration\n\n## 🚀 **APIs \u0026 Communication**\n\n- **REST API** - Fastify Clean HTTP endpoints\n- **GraphQL API** - Optional GraphQL schema with resolvers\n- **OpenAPI/Swagger** - Interactive API documentation\n- **Event Streaming** - Kafka producer/consumer for user lifecycle events\n- **Background Jobs** - BullMQ for async tasks\n\n## 🔧 Microservice features (details)\n\n- **Service Discovery** - Consul integration for service registration\n- **Distributed Tracing** - Jaeger integration for request tracing\n- **Health Checks** - Comprehensive health monitoring endpoints\n- **Configuration Management** - Environment-based configuration\n- **Graceful Shutdown** - Proper resource cleanup on termination\n- **Message Queues** - Optional Kafka/BullMQ for async tasks\n- **Real-time** - WebSocket support for live updates\n\n## 🔧 **Optional Advanced Features**\n\nAll features disabled by default - enable what you need:\n\n- **Microservice Transports** - TCP, Redis, NATS, RabbitMQ (set `ENABLE_*_MICROSERVICE=true`)\n- **Service Discovery** - Consul integration (set `ENABLE_CONSUL_DISCOVERY=true`)\n- **Distributed Tracing** - Jaeger integration (set `ENABLE_JAEGER_TRACING=true`)\n- **Circuit Breakers** - Resilience patterns (set `ENABLE_CIRCUIT_BREAKER=true`)\n- **Performance Monitoring** - Metrics collection (set `ENABLE_PERFORMANCE_MONITORING=true`)\n- **Advanced Caching** - Redis cache (set `ENABLE_REDIS_CACHE=true`)\n\n**Philosophy:** Template includes everything but enables only essentials by default.\n\n## 🧪 **Testing \u0026 Quality**\n\n- **Unit Tests** - Comprehensive test coverage with mocking\n- **Integration Tests** - Real database testing capabilities\n- **E2E Tests** - Full application flow testing\n- **Performance Tests** - Load testing with concurrent requests\n- **Code Quality** - ESLint, Prettier, and pre-commit hooks\n\n## 🐳 **DevOps \u0026 Deployment**\n\n- **Docker Support** - Multi-stage builds and compose files\n- **Kubernetes Ready** - Helm charts for K8s deployment\n- **CI/CD Pipeline** - GitHub Actions with automated testing\n- **Production Monitoring** - Health checks and observability\n- **Environment Management** - Development, staging, and production configs\n\n## 🚀 **Quick Start**\n\n### 1. Required Environment Setup\n\n```bash\n# Copy environment template (simplified configuration)\ncp .env.example .env\n\n# For advanced features (MQTT, NATS, gRPC, advanced observability):\n# cp .env.example.legacy .env\n\n# Configure database type (postgresql, mysql/mariadb or mongodb)\nDATABASE_TYPE=postgresql  # or mysql | mariadb | mongodb\nDATABASE_URL=postgresql://dev:dev@localhost:5432/dev\n# For MySQL/MariaDB:\n# MYSQL_URL=mysql://dev:dev@localhost:3306/dev\n# MONGODB_URL=mongodb://dev:dev@localhost:27017/nestjs-app\n\n# Security (REQUIRED)\nJWT_SECRET=your-strong-secret-key-change-in-production\nALLOWED_ORIGINS=https://yourdomain.com,https://api.yourdomain.com\n\n# Services\nREDIS_URL=redis://localhost:6379\nKAFKA_BROKERS=localhost:9092\n\n# Microservices (Optional)\nCONSUL_HOST=localhost\nCONSUL_PORT=8500\nJAEGER_ENDPOINT=http://localhost:14268/api/traces\n\n# Protocols (Optional)\nSSL_CERT_PATH=/path/to/cert.pem\nSSL_KEY_PATH=/path/to/key.pem\nMQTT_BROKER_URL=mqtt://localhost:1883\nGRPC_PORT=5000\n\n# Security Settings\nRATE_LIMIT_MAX=100\nRATE_LIMIT_WINDOW=60000\nBODY_LIMIT=1048576\n\n# Email/SMTP Configuration\nSMTP_HOST=smtp.gmail.com\nSMTP_PORT=587\nSMTP_SECURE=false\nSMTP_USER=your-email@gmail.com\nSMTP_PASS=your-app-password\nSMTP_FROM=your-email@gmail.com\n\n# Feature Flags - Protocols\nENABLE_WEBSOCKET=true\nENABLE_MQTT=false\nENABLE_HTTPS=true\nENABLE_GRPC=false\n\n# Feature Flags - Services\nENABLE_JAEGER_TRACING=false\nENABLE_REDIS_CACHE=true\nENABLE_CONSUL_DISCOVERY=false\nENABLE_CIRCUIT_BREAKER=false\nENABLE_PERFORMANCE_MONITORING=false\nENABLE_EMAIL_SERVICE=true\n\n```\n\n## Environment Variables Reference\n\n### Database Configuration\n\n- `DATABASE_TYPE`: Database type selection (`postgresql`, `mysql`, `mariadb` or `mongodb`)\n- `DATABASE_URL`: PostgreSQL connection string\n- `MYSQL_URL`: MySQL/MariaDB connection string (used when `DATABASE_TYPE` is `mysql` or `mariadb`)\n- `MONGODB_URL`: MongoDB connection string\n\n### Authentication \u0026 Security\n\n- `JWT_SECRET`: Secret key for JWT token signing (required in production)\n- `ACCESS_TOKEN_EXP`: Access token expiration time (default: 15m)\n- `REFRESH_TOKEN_EXP`: Refresh token expiration time (default: 7d)\n- `ALLOWED_ORIGINS`: CORS allowed origins (comma-separated)\n- `RATE_LIMIT_MAX`: Maximum requests per window (default: 100)\n- `RATE_LIMIT_WINDOW`: Rate limit window in ms (default: 60000)\n- `BODY_LIMIT`: Request body size limit in bytes (default: 1048576)\n\n### Service Configuration\n\n- `SERVICE_NAME`: Microservice identifier\n- `SERVICE_VERSION`: Service version for discovery\n- `SERVICE_HOST`: Service host binding\n- `PORT`: HTTP server port (default: 3000)\n\n### External Services\n\n- `REDIS_URL`: Redis connection string for caching and sessions\n- `KAFKA_BROKERS`: Kafka broker addresses (comma-separated)\n- `CONSUL_HOST`: Consul server host for service discovery\n- `CONSUL_PORT`: Consul server port (default: 8500)\n- `JAEGER_ENDPOINT`: Jaeger tracing endpoint URL\n\n### Protocol Configuration\n\n- `SSL_CERT_PATH`: SSL certificate file path for HTTPS\n- `SSL_KEY_PATH`: SSL private key file path for HTTPS\n- `MQTT_BROKER_URL`: MQTT broker connection URL\n- `MQTT_USERNAME`: MQTT authentication username\n- `MQTT_PASSWORD`: MQTT authentication password\n- `WS_PORT`: WebSocket server port (default: 3001)\n- `GRPC_PORT`: gRPC server port (default: 5000)\n\n### Email Configuration\n\n- `SMTP_HOST`: SMTP server hostname\n- `SMTP_PORT`: SMTP server port (default: 587)\n- `SMTP_SECURE`: Use secure connection (default: false)\n- `SMTP_USER`: SMTP authentication username\n- `SMTP_PASS`: SMTP authentication password\n- `SMTP_FROM`: Default sender email address\n\n### Application Settings\n\n- `NODE_ENV`: Environment mode (`development`, `production`, `test`)\n- `LOG_LEVEL`: Logging level (`info`, `debug`, `warn`, `error`)\n- `APP_URL`: Application base URL for links\n- `API_BASE_URL`: API base URL for external references\n\n### 2. Install Dependencies\n\n```bash\npnpm install\n```\n\n### 3. Start Services\n\n```bash\n# Basic services (PostgreSQL, Redis, Kafka)\npnpm docker:up\n\n# Full stack with MongoDB, Consul, Jaeger (OTel enabled)\npnpm docker:full\n```\n\n### 4. Database Setup\n\n**PostgreSQL:**\n\n```bash\npnpm prisma:generate\npnpm prisma:migrate:dev\npnpm prisma:seed\n```\n\n**MongoDB:**\n\n```bash\npnpm mongodb:migrate\nMONGODB_URL=mongodb://user:pass@localhost:27017/db\n```\n\n### 5. Start Application\n\n```bash\npnpm start:dev\n```\n\n### 6. Run Tests\n\n```bash\n# Unit tests only\npnpm test:unit\n\n# All tests (unit + e2e with mocked DB)\npnpm test:all\n\n# Full test suite (unit + integration + E2E mocked DB)\npnpm test:full\n\n# Full REAL E2E (hits Postgres/Redis/Kafka from docker:full)\npnpm test:e2e:real\n```\n\n## 🗄️ **Database Configuration**\n\n### PostgreSQL (Default)\n\n```bash\nDATABASE_TYPE=postgresql\nDATABASE_URL=postgresql://user:pass@localhost:5432/db\n```\n\n### MySQL / MariaDB\n\nSet the database type and URL, then generate Prisma client and run migrations:\n\n```bash\nDATABASE_TYPE=mysql # or mariadb\nMYSQL_URL=mysql://user:pass@localhost:3306/db\n```\n\nNotes:\n\n- Prisma schema provider must match the selected engine. This repo includes a small helper script that switches the Prisma datasource `provider` based on `DATABASE_TYPE` automatically before `prisma generate` and `start:dev`.\n- For a fresh MySQL/MariaDB setup, run:\n  - pnpm prisma:generate\n  - pnpm prisma:migrate:dev --name init\n  - pnpm prisma:seed (optional)\n- Existing PostgreSQL migrations won’t apply to MySQL. Create new migrations when switching engines in development.\n\n### MongoDB\n\n```bash\nDATABASE_TYPE=mongodb\n```\n\nThe application automatically selects the appropriate repository implementation based on `DATABASE_TYPE`.\n\n- Prisma (PostgreSQL): Prisma manages connections internally. In production, it’s recommended to front Postgres with PgBouncer and point `DATABASE_URL` to the pooler for robust pooling at scale.\n  - You can override the datasource URL at runtime via `DATABASE_URL` (already wired in `PrismaService`).\n- MongoDB: The driver’s pool is enabled by default. You can tune with optional envs:\n  - `MONGODB_MAX_POOL_SIZE`, `MONGODB_MIN_POOL_SIZE`, `MONGODB_MAX_IDLE_TIME_MS`, `MONGODB_WAIT_QUEUE_TIMEOUT_MS`\n\nDocker full stack includes a PgBouncer service. The app is preconfigured to use it in `docker/docker-compose.full.yml`:\n\n```yaml\nDATABASE_URL: 'postgresql://dev:dev@pgbouncer:6432/dev?pgbouncer=true'\n```\n\n## 🔧 **Microservice Features**\n\n### Service Discovery (Consul)\n\n```bash\nCONSUL_HOST=localhost\nCONSUL_PORT=8500\nSERVICE_NAME=nestjs-api\n```\n\n### Distributed Tracing (Jaeger)\n\n```bash\nJAEGER_ENDPOINT=http://localhost:14268/api/traces\n```\n\n### Event Streaming (Kafka)\n\n```bash\nKAFKA_BROKERS=localhost:9092\n```\n\n### Background Jobs (BullMQ + Redis)\n\n```bash\nREDIS_URL=redis://localhost:6379\n```\n\n### Circuit Breaker (Fastify + programmatic)\n\nEnable a service-wide circuit breaker to protect endpoints and wrap outbound calls.\n\nEnv flags:\n\n```env\nENABLE_CIRCUIT_BREAKER=true\n# Trip circuit after N consecutive failures\nCB_THRESHOLD=5\n# Per-request timeout (ms) before considering a failure\nCB_TIMEOUT=2000\n# Time (ms) to stay open before trying a half-open probe\nCB_RESET_TIMEOUT=10000\n```\n\nBehavior:\n\n- When the threshold is reached, requests get HTTP 503 with message \"Circuit open\" until reset timeout elapses.\n- After `CB_RESET_TIMEOUT`, one request is allowed in half-open state to probe recovery.\n- The Fastify plugin is applied globally to all routes when enabled.\n\nProgrammatic usage for outbound HTTP calls (via `HttpClientService`):\n\n```ts\n// Example\nawait httpClient.fetch('https://api.example.com', { timeoutMs: 1500, cbName: 'upstreamA' });\n```\n\nIntrospection endpoint:\n\n```bash\ncurl http://localhost:3000/health/circuit/global\n```\n\nNotes: Uses @fastify/circuit-breaker (Fastify v4 compatible). E2E tests cover open/half-open/close semantics.\n\n## Storage (S3 / Azure Blob / GCS / In-memory)\n\nA pluggable storage service with a simple interface for upload/download/list/delete and signed URLs. By default, an in-memory adapter is used (great for tests). Cloud adapters are wired to their real SDKs but are disabled by default behind a feature flag.\n\nEnv flags:\n\n```env\n# Master on/off switch (defaults to false → memory adapter)\nENABLE_STORAGE=false\n\n# Select provider: aws | azure | gcp | none (defaults to none → in-memory)\nSTORAGE_PROVIDER=none\n\n# AWS S3 (when STORAGE_PROVIDER=aws)\nS3_BUCKET=your-bucket\nS3_REGION=us-east-1\nS3_ACCESS_KEY_ID=...\nS3_SECRET_ACCESS_KEY=...\n# Optional for S3-compatible stores (e.g., MinIO):\nS3_ENDPOINT=http://localhost:9000\n\n# Azure Blob (when STORAGE_PROVIDER=azure)\nAZURE_BLOB_CONNECTION_STRING=...\nAZURE_BLOB_CONTAINER=your-container\n\n# Google Cloud Storage (when STORAGE_PROVIDER=gcp)\nGCP_PROJECT_ID=your-project\nGCS_BUCKET=your-bucket\n# One of these (standard GCP ways to auth):\nGOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json\n# or\nGCP_APPLICATION_CREDENTIALS=/path/to/key.json\n```\n\nStreaming usage (large files) via demo endpoints in development/test environments:\n\n- Upload (optionally gzip on the fly):\n  - curl -X POST --data-binary @bigfile.bin \"\u003chttp://localhost:3000/demo/upload-stream?key=big.bin\u0026gzip=1\u003e\"\n- Download (optionally gunzip on the fly):\n  - curl -L \"\u003chttp://localhost:3000/demo/download-stream?key=big.bin\u0026gunzip=1\u003e\" -o out.bin\n\nProgrammatic usage example:\n\n```ts\nimport { Controller, Post, Get, Param, Body } from '@nestjs/common';\nimport { StorageService } from '@/common/storage/storage.service';\n\n@Controller('files')\nexport class FilesController {\n  constructor(private readonly storage: StorageService) {}\n\n  @Post()\n  async upload(@Body() body: { key: string; content: string }) {\n    await this.storage.upload(body.key, Buffer.from(body.content, 'utf8'), {\n      contentType: 'text/plain',\n    });\n    return { ok: true };\n  }\n\n  @Get(':key')\n  async get(@Param('key') key: string) {\n    const buf = await this.storage.download(key);\n    return buf.toString('utf8');\n  }\n}\n```\n\n## �🛠️ **Development Workflow**\n\n### Code Quality\n\n- **Linting**: `pnpm lint` - ESLint with TypeScript support\n- **Formatting**: `pnpm format` - Prettier code formatting\n- **Pre-commit hooks**: Automatically run linting, formatting, and unit tests\n- **Pre-push hooks**: Run full test suite before pushing\n\n### Testing\n\n- **Unit tests**: `pnpm test:unit` - 90 tests with full mocking\n- **E2E tests**: `pnpm test:e2e` - Application startup and endpoint tests\n- **All tests**: `pnpm test:all` - Test suite for CI/CD\n- **Coverage**: Add `--coverage` flag to any test command for coverage reports\n\nAll tests use comprehensive mocking (Prisma, Redis, bcrypt) and run without external dependencies.\n\n## 🔐 **Authentication \u0026 Authorization**\n\n### Auth Endpoints\n\n- **Register**: `POST /auth/register` - Create new user account\n- **Login**: `POST /auth/login` - Authenticate and get tokens\n- **Refresh**: `POST /auth/refresh` - Refresh access token\n- **Logout**: `POST /auth/logout` - Revoke refresh token\n- **Profile**: `GET /auth/profile` - Get current user (protected)\n- **Users**: `GET /auth/users` - List all users (admin only)\n\n### Security Features\n\n- **JWT Tokens**: Short-lived access tokens (15m) + refresh tokens (7d)\n- **Token Revocation**: Redis-based blacklist for immediate logout\n- **Password Security**: bcrypt hashing with configurable rounds\n- **Rate Limiting**: Configurable request limits per IP\n- **CORS Protection**: Environment-based origin restrictions\n- **Security Headers**: Helmet integration with CSP\n- **Input Validation**: Comprehensive validation with sanitization\n\n### Role-Based Access Control (RBAC)\n\n- **CASL Integration**: Fine-grained permission system\n- **Policy Guards**: Declarative permission checks\n- **Role Management**: User and admin roles with different capabilities\n- **Resource Protection**: Method-level authorization\n\n## 🌐 **API Access**\n\n### REST API\n\n- **Base URL**: `http://localhost:3000`\n- **Documentation**: `http://localhost:3000/api` (Swagger UI)\n- **OpenAPI Spec**: `http://localhost:3000/api-json`\n- **Health Check**: `http://localhost:3000/health`\n\n### GraphQL API\n\n- **Endpoint**: `http://localhost:3000/graphql`\n- **Playground**: `http://localhost:3000/graphql` (development mode)\n- **Schema**: Auto-generated from resolvers\n- **Introspection**: Enabled in development\n\n### Schema Documentation\n\n- **GraphQL Schema**: `http://localhost:3000/schemas/graphql`\n- **Kafka Events**: `http://localhost:3000/schemas/kafka`\n- **All Schemas**: `http://localhost:3000/schemas`\n\n### Monitoring \u0026 Observability\n\n- **Health Checks**: `http://localhost:3000/health`\n- **Readiness**: `http://localhost:3000/health/ready`\n- **Liveness**: `http://localhost:3000/health/live`\n- **Jaeger UI**: `http://localhost:16686` (when enabled)\n- **Consul UI**: `http://localhost:8500` (when enabled)\n\n## Observability (OpenTelemetry + Logging)\n\nThis template includes OpenTelemetry (OTel) support for distributed tracing and metrics, plus structured logs enriched with correlation metadata.\n\n### Enable OTel\n\nSet the following in your `.env`:\n\n```env\nENABLE_OPENTELEMETRY=true\nSERVICE_NAME=nestjs-mstv\n\n# Traces (OTLP over HTTP)\nOTEL_TRACES_EXPORTER=otlp\nOTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318\n# Optional auth headers (JSON or comma-separated key=value pairs)\n# OTEL_EXPORTER_OTLP_HEADERS=api-key=xxx\n\n# Metrics (choose one)\nOTEL_METRICS_EXPORTER=none     # prometheus | otlp | none\nENABLE_PROMETHEUS_METRICS=false\nPROMETHEUS_HOST=0.0.0.0\nPROMETHEUS_PORT=9464\n\n# Convenience endpoints (OTLP-compatible)\n# SigNoz\nENABLE_SIGNOZ_TRACING=false\nSIGNOZ_ENDPOINT=http://localhost:4318/v1/traces\n\n# Datadog\nENABLE_DATADOG_TRACING=false\nDATADOG_OTLP_ENDPOINT=http://localhost:4318/v1/traces\n```\n\nThe app auto-initializes OTel at startup when `ENABLE_OPENTELEMETRY=true`.\n\n### Exporters\n\n- Jaeger (via OTLP): set `OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger-collector:4318`\n- SigNoz: set `SIGNOZ_ENDPOINT=http://signoz-otel-collector:4318/v1/traces` (or use `OTEL_EXPORTER_OTLP_ENDPOINT`)\n- Datadog: set `DATADOG_OTLP_ENDPOINT=http://datadog-agent:4318/v1/traces` (or use `OTEL_EXPORTER_OTLP_ENDPOINT` and headers)\n- Prometheus metrics: set `ENABLE_PROMETHEUS_METRICS=true` (scrape `http://host:9464/metrics`)\n- OTLP metrics: set `OTEL_METRICS_EXPORTER=otlp` and `OTEL_EXPORTER_OTLP_ENDPOINT`\n\nNotes\n\n- All three backends (Jaeger, SigNoz, Datadog) can ingest OTLP; pick the URL that matches your setup.\n- Optional headers for auth can be provided via `OTEL_EXPORTER_OTLP_HEADERS`.\n\n### Log Correlation\n\nPino logs automatically include these fields per request:\n\n- `traceId`, `requestId`, `userId`, `method`, `url`, `ip`, plus `service` and `env`.\n\nEvery HTTP response also includes the headers:\n\n- `x-trace-id` and `x-request-id` for cross-system correlation.\n\nIf OpenTelemetry is enabled, the logger will reuse the active OTel trace id, aligning logs with traces.\n\n## API Examples\n\n### REST Endpoints\n\n```bash\n# Register user\ncurl -X POST http://localhost:3000/auth/register \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"email\":\"user@example.com\",\"password\":\"password123\",\"name\":\"John Doe\"}'\n\n# Login\ncurl -X POST http://localhost:3000/auth/login \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"email\":\"user@example.com\",\"password\":\"password123\"}'\n\n# Get profile (with JWT token)\ncurl -X GET http://localhost:3000/auth/profile \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n```\n\n### GraphQL Queries\n\n```graphql\n# Register user\nmutation {\n  register(input: { email: \"user@example.com\", password: \"password123\", name: \"John Doe\" }) {\n    id\n    email\n    name\n    role\n  }\n}\n\n# Login\nmutation {\n  login(input: { email: \"user@example.com\", password: \"password123\" }) {\n    access_token\n    refresh_token\n    user {\n      id\n      email\n      name\n      role\n    }\n  }\n}\n\n# Get current user\nquery {\n  me {\n    id\n    email\n    name\n    role\n  }\n}\n\n# Get all users (admin only)\nquery {\n  getAllUsers {\n    id\n    email\n    name\n    role\n    createdAt\n  }\n}\n```\n\n## 📨 **Event-Driven Architecture**\n\n### Kafka Events\n\n- **User Events**: `user.registered`, `user.updated`, `user.deleted`\n- **Auth Events**: `user.logged_in`, `user.logged_out`, `token.refreshed`\n- **Email Events**: `email.welcome`, `email.password_reset`, `email.verification`\n\n### Background Jobs (BullMQ)\n\n- **Email Processing**: Welcome emails, password resets, verification (provider not implemented)\n- **Queue Management**: Job retry logic and dead letter queues\n- **Monitoring**: Queue statistics and job status tracking\n\n### Event Schema\n\nAll events follow standardized schemas defined in `/src/schemas/kafka.schemas.ts`:\n\n```typescript\n{\n  event: 'user.registered',\n  userId: 'cuid123',\n  email: 'user@example.com',\n  timestamp: '2023-01-01T00:00:00.000Z'\n}\n```\n\n## 🐳 **Docker \u0026 Deployment**\n\n### Development\n\n```bash\n# Basic services\ndocker-compose -f docker/docker-compose.yml up -d\n\n# Full microservice stack\ndocker-compose -f docker/docker-compose.full.yml up -d\n```\n\n### Production (Kubernetes)\n\n```bash\n# Deploy with Helm\nhelm upgrade --install nestjs-api ./helm/nest-ddd-chart\n\n# With custom values\nhelm upgrade --install nestjs-api ./helm/nest-ddd-chart -f values.prod.yaml\n```\n\n### CI/CD Pipeline\n\n- **GitHub Actions**: Automated testing and deployment\n- **Multi-stage builds**: Optimized Docker images\n- **Health checks**: Kubernetes readiness and liveness probes\n- **Rolling updates**: Zero-downtime deployments\n\n## 🧪 **Testing Guide**\n\nComprehensive testing strategy with multiple test types and environments.\n\n## 🧪 **Test Types**\n\n### Unit Tests\n\n- **Command**: `pnpm test:unit`\n- **Coverage**: 90 tests covering core business logic\n- **Mocks**: All external dependencies (Prisma, Redis, Kafka, BullMQ)\n- **Speed**: Fast execution for development feedback\n\n### Integration Tests\n\n- **Command**: `pnpm test:integration`\n- **Purpose**: Test with real database connections\n- **Setup**: Requires running database services\n- **Scope**: Database operations and service interactions\n\n### E2E Tests (Mock)\n\n- **Command**: `pnpm test:e2e`\n- **Purpose**: Application startup and endpoint availability\n- **Environment**: No external dependencies required\n- **CI/CD**: Suitable for continuous integration\n\n### E2E Tests (Full)\n\n- **Command**: `pnpm test:e2e:full`\n- **Purpose**: Application flows with real services\n- **Environment**: Full Docker stack required\n- **Scope**: End-to-end user journeys\n\n### Performance Tests\n\n- **Command**: `pnpm test:performance`\n- **Purpose**: Load testing and concurrent request handling\n- **Metrics**: Response times and throughput measurement\n- **Location**: `test/performance/load.test.ts`\n\n### Test Commands\n\n```bash\n# Quick feedback loop\npnpm test:unit\n\n# CI/CD pipeline\npnpm test:all\n\n# Full validation\npnpm test:full\n\n# With coverage\npnpm test:unit --coverage\n```\n\n## Mock Configuration\n\n### Global Mocks (test/setup.ts)\n\n- Prisma Client with CRUD operations\n- Redis client with get/set/del operations\n- bcrypt for password hashing\n- Kafka producer/consumer\n- BullMQ queue and worker\n\n### E2E Mocks (test/setup.e2e.mock.ts)\n\n- Enhanced Prisma mocks with conditional responses\n- Redis mocks for token management\n- bcrypt mocks for authentication\n\n## Test Environment\n\n- **NODE_ENV**: Set to 'test' automatically\n- **JWT_SECRET**: Test-specific secret\n- **DATABASE_URL**: Mock URL to prevent real connections\n- **REDIS_URL**: Mock URL for Redis operations\n\n## Authentication in Tests\n\nThe `PoliciesGuard` includes special handling for test environments:\n\n- Automatically provides mock admin user when `NODE_ENV=test`\n- Allows testing protected endpoints without JWT setup\n- Gracefully handles missing context methods in test mocks\n\n## Running Tests\n\n```bash\n# Run all tests (recommended for CI)\npnpm test:all\n\n# Run specific test types\npnpm test:unit\npnpm test:e2e\npnpm test:e2e:full\n\n# Run with coverage\npnpm test:unit --coverage\n\n# Run specific test file\npnpm test:unit test/auth.service.spec.ts\n```\n\n## Test Structure\n\n```text\ntest/\n├── e2e/                    # End-to-end tests\n│   ├── mock.e2e.spec.ts   # Basic app startup tests\n│   ├── auth.e2e.spec.ts   # Authentication flow tests\n│   ├── graphql.e2e.spec.ts # GraphQL API tests\n│   └── users.e2e.spec.ts  # User management tests\n├── setup.ts               # Global test setup with mocks\n├── setup.e2e.mock.ts      # E2E test setup with enhanced mocks\n└── *.spec.ts              # Unit test files\n```\n\n## CI/CD Integration\n\nThe project is configured for GitHub Actions with:\n\n- Pre-commit hooks running unit tests\n- Pre-push hooks running all tests\n- CI pipeline running `pnpm test:all`\n\nAll tests run without external dependencies, making them suitable for any CI environment.\n\n## 🐳 **Docker Testing**\n\n### **Container E2E Tests**\n\n```bash\n# Run tests in Docker container (no external dependencies)\ndocker-compose -f docker/docker-compose.simple-test.yml up --build --abort-on-container-exit\n\n# Run tests with real database services\ndocker-compose -f docker/docker-compose.test.yml up --build --abort-on-container-exit\n\n# Clean up after tests\ndocker-compose -f docker/docker-compose.test.yml down --volumes\n```\n\n### **Docker Build Testing**\n\n```bash\n# Test Docker build process\ndocker build -f docker/Dockerfile -t nestjs-test .\n\n# Validate Docker Compose configurations\ndocker-compose -f docker/docker-compose.yml config\ndocker-compose -f docker/docker-compose.test.yml config\n```\n\n### **Available Docker Configurations**\n\n- **docker-compose.yml** - Development with PostgreSQL, Redis, Kafka\n- **docker-compose.full.yml** - Full stack with MongoDB, Consul, Jaeger\n- **docker-compose.test.yml** - Testing with real database services\n- **docker-compose.simple-test.yml** - Testing without external dependencies\n\n## 🏢 **CQRS Architecture**\n\n## 📝 **CQRS Implementation**\n\n### **Command Query Responsibility Segregation**\n\n- **Write Operations** - Commands handled by CommandBus\n- **Read Operations** - Queries handled by QueryBus\n- **Event Processing** - Events handled by EventBus\n- **Auto-discovery** - Handlers registered automatically via decorators\n\n### **Architecture Flow**\n\n```text\nCommands → CommandBus → CommandHandlers → Repository → Events\nQueries → QueryBus → QueryHandlers → Repository → Results\nEvents → EventBus → EventHandlers → Side Effects\n```\n\n### **Available Commands**\n\n- **CreateUserCommand** - Create new user with validation\n- **UpdateUserCommand** - Update user information\n- **DeleteUserCommand** - Remove user from system\n\n### **Available Queries**\n\n- **GetUserQuery** - Retrieve user by ID\n- **GetAllUsersQuery** - List all users with pagination\n\n### **Available Events**\n\n- **UserCreatedEvent** - Published when user is created\n- **UserUpdatedEvent** - Published when user is modified\n- **UserDeletedEvent** - Published when user is removed\n\n## 💻 **CQRS Usage Examples**\n\n### **Command Usage**\n\n```typescript\n// In your service\nconst user = await this.commandBus.execute(\n  new CreateUserCommand('user@example.com', 'password123', 'John Doe')\n);\n```\n\n### **Query Usage**\n\n```typescript\n// In your service\nconst user = await this.queryBus.execute(new GetUserQuery('user-id-123'));\n\nconst users = await this.queryBus.execute(\n  new GetAllUsersQuery(10, 0) // limit, offset\n);\n```\n\n### **Event Handling**\n\n```typescript\n@EventHandler(UserCreatedEvent)\nexport class UserCreatedHandler implements IEventHandler\u003cUserCreatedEvent\u003e {\n  async handle(event: UserCreatedEvent): Promise\u003cvoid\u003e {\n    // Send welcome email, update analytics, etc.\n  }\n}\n```\n\n### **Testing CQRS**\n\n```bash\n# Run CQRS-specific tests\npnpm test test/cqrs.spec.ts\n\n# All CQRS tests are included in unit tests\npnpm test:unit\n```\n\n## 🔧 **Creating Custom CQRS Components**\n\n### **1. Create a Command**\n\n```typescript\nexport class YourCommand implements ICommand {\n  readonly type = 'YourCommand';\n  constructor(public readonly data: any) {}\n}\n```\n\n### **2. Create a Command Handler**\n\n```typescript\n@Injectable()\n@CommandHandler(YourCommand)\nexport class YourCommandHandler implements ICommandHandler\u003cYourCommand\u003e {\n  async execute(command: YourCommand): Promise\u003cany\u003e {\n    // Handle command logic\n  }\n}\n```\n\n### **3. Register in Module**\n\n```typescript\n@Module({\n  imports: [CqrsModule],\n  providers: [YourCommandHandler],\n})\nexport class YourModule {}\n```\n\n## 🌐 **Multi-Protocol Examples**\n\n## **Protocol Usage Examples**\n\n### **HTTPS Secure Requests**\n\n```typescript\n// Configure SSL certificates\nSSL_CERT_PATH = /path/ot / cert.pem;\nSSL_KEY_PATH = /path/ot / key.pem;\n\n// Make secure API calls\nconst httpsService = new HttpsService(new FeatureFlagsService());\nconst response = await httpsService.makeSecureRequest('https://api.example.com/data');\n```\n\n### **WebSocket Real-time Communication**\n\n```javascript\n// Client-side WebSocket connection\nconst socket = io('ws://localhost:3000/ws');\n\n// Send message\nsocket.emit('message', { text: 'Hello WebSocket!' });\n\n// Join room for targeted messaging\nsocket.emit('join-room', 'user-notifications');\n\n// Listen for responses\nsocket.on('response', (data) =\u003e console.log(data));\n```\n\n### **MQTT IoT Messaging**\n\n```bash\n# Configure MQTT broker\nMQTT_BROKER_URL=mqtt://localhost:1883\nMQTT_USERNAME=your_username\nMQTT_PASSWORD=your_password\n```\n\n```ts\n// Publish user events\nmqttService.publishUserEvent('user123', 'login', { ip: '192.168.1.1' });\n\n// Publish system alerts\nmqttService.publishSystemAlert('error', 'Database connection failed');\n\n// Subscribe to topics\nmqttService.subscribe('sensors/temperature');\n```\n\n### **gRPC High-Performance RPC**\n\n```bash\n# Configure gRPC\nGRPC_PORT=5000\n```\n\n```ts\n// gRPC client usage\nconst client = new UserServiceClient('localhost:5000');\n\n// Create user via gRPC\nconst user = await client.createUser({\n  email: 'user@example.com',\n  name: 'John Doe',\n  password: 'secure123',\n});\n\n// Get user via gRPC\nconst userData = await client.getUser({ id: 'user123' });\n```\n\n### **Testing Protocols**\n\n```bash\n# Test all protocol implementations\npnpm test test/protocols.spec.ts\n\n# Protocol tests are included in unit tests\npnpm test:unit\n```\n\n## 🔒 **Security Implementation**\n\n## 🛡️ **Multi-Layer Security**\n\n### 1. Helmet (@fastify/helmet)\n\n- **Content Security Policy (CSP)**: Prevents XSS attacks\n- **X-Frame-Options**: Prevents clickjacking (set to DENY)\n- **X-Content-Type-Options**: Prevents MIME type sniffing\n- **Referrer-Policy**: Controls referrer information\n\n### 2. Rate Limiting (@fastify/rate-limit)\n\n- **Default**: 100 requests per minute per IP\n- **Configurable**: Via `RATE_LIMIT_MAX` and `RATE_LIMIT_WINDOW` env vars\n- **IP-based**: Uses client IP for rate limiting\n- **Graceful**: Skips on error to maintain availability\n\n### 3. Compression (@fastify/compress)\n\n- **Encodings**: gzip, deflate\n- **Performance**: Reduces bandwidth usage\n\n### 4. Sensible Defaults (@fastify/sensible)\n\n- **HTTP errors**: Standardized error responses\n- **Utilities**: Common HTTP status codes and helpers\n\n## Security Headers\n\n### Custom Security Headers (via Fastify hooks)\n\n- **X-Frame-Options**: DENY\n- **X-Content-Type-Options**: nosniff\n- **Referrer-Policy**: strict-origin-when-cross-origin\n- **Permissions-Policy**: Restricts geolocation, microphone, camera\n\n### Cache Control for Sensitive Endpoints\n\n- **Auth endpoints** (`/auth/*`): No caching\n- **User endpoints** (`/users/*`): No caching\n- **Headers**: Cache-Control, Pragma, Expires\n\n## CORS Configuration\n\n### Development (CORS)\n\n- **Origin**: Allow all origins\n- **Credentials**: Enabled\n\n### Production (CORS)\n\n- **Origin**: Restricted to `ALLOWED_ORIGINS` env var\n- **Methods**: GET, POST, PUT, DELETE, OPTIONS only\n- **Credentials**: Enabled for authenticated requests\n\n## Input Validation \u0026 Sanitization\n\n### Global Validation Pipe\n\n- **Whitelist**: Only allow defined properties\n- **Transform**: Auto-transform input types\n- **Forbid non-whitelisted**: Reject unknown properties\n- **Production**: Disable detailed error messages\n\n### Body Limits\n\n- **Default**: 1MB request body limit\n- **Configurable**: Via `BODY_LIMIT` env var\n- **Protection**: Prevents DoS via large payloads\n\n## Authentication \u0026 Authorization\n\n### JWT Security\n\n- **Secret**: Configurable via `JWT_SECRET` env var\n- **Expiration**: Short-lived access tokens (15m default)\n- **Refresh tokens**: Longer-lived, stored securely\n\n### Token Revocation\n\n- **Redis-based**: Revoked tokens stored in Redis\n- **Logout**: Immediate token invalidation\n- **Security**: Prevents token reuse after logout\n\n### Role-based Access Control (RBAC)\n\n- **CASL integration**: Fine-grained permissions\n- **Guards**: Protect sensitive endpoints\n- **Policies**: Declarative permission checks\n\n## Production Security\n\n### Environment-based Configuration\n\n- **Swagger UI**: Disabled in production\n- **Error messages**: Sanitized in production\n- **Host binding**: Secure host binding for production\n\n### Trust Proxy\n\n- **Enabled**: For proper IP detection behind proxies\n- **Rate limiting**: Accurate IP-based limiting\n- **Security headers**: Proper forwarded headers handling\n\n## Security Environment Variables\n\n### Required Security Variables\n\n```env\nJWT_SECRET=your-strong-secret-key\nALLOWED_ORIGINS=https://yourdomain.com,https://api.yourdomain.com\nRATE_LIMIT_MAX=100\nRATE_LIMIT_WINDOW=60000\nBODY_LIMIT=1048576\n```\n\n## Security Best Practices Implemented\n\n1. **Defense in Depth**: Multiple security layers\n2. **Principle of Least Privilege**: Minimal permissions by default\n3. **Input Validation**: All inputs validated and sanitized\n4. **Secure Headers**: Comprehensive security headers\n5. **Rate Limiting**: Protection against abuse\n6. **HTTPS Ready**: Secure transport layer support\n7. **Error Handling**: No sensitive information in errors\n8. **Token Security**: Secure JWT implementation with revocation\n\n## Security Testing\n\nAll security measures are tested in the test suite:\n\n- Unit tests for authentication logic\n- E2E tests for endpoint security\n- Validation tests for input sanitization\n- Authorization tests for access control\n\n## Monitoring \u0026 Logging\n\n- **Request logging**: All requests logged with IP and user agent\n- **Error logging**: Security-relevant errors logged\n- **Rate limit logging**: Abuse attempts logged\n- **Authentication logging**: Login/logout events logged\n\n## Security Updates\n\nRegular updates of dependencies and security patches:\n\n- Automated dependency scanning\n- Security vulnerability monitoring\n- Regular security audits\n\n---\n\n## 🧭 Coordination with Temporal (Cron + Orchestration + Signals)\n\nThis template includes an optional hybrid coordination package using Temporal to support:\n\n- Cron schedules (Temporal Schedules)\n- Orchestration (Saga-style workflows + compensations)\n- Choreography via Signals (external services signaling progress)\n\nDocs: see `coordination/README.md`.\n\nQuick commands:\n\n```bash\n# Start local Temporal and UI\nnpm run coordination:temporal:up\n\n# Run the coordination worker\nnpm run coordination:worker\n\n# Run the hybrid smoke (starts workflow and signals it)\nnpm run coordination:smoke\n\n# One-step orchestrated smoke (brings up Temporal, starts worker, runs smoke)\nnpm run coordination:smoke:local\n\n# Tear down local Temporal\nnpm run coordination:temporal:down\n```\n\n## 📐 Architecture Diagrams\n\nThese diagrams illustrate how this template can be used in different setups. They are examples; tailor to your needs.\n\n### 1) Core architecture (single service)\n\n![Core architecture](diagrams/svg/core_architecture.svg)\n\n### 2) Multi-microservice with API Gateway\n\n![Multi-microservice with API Gateway](diagrams/svg/multi_microservice_gateway.svg)\n\n### 3) Choreography (event-driven) between services\n\n![Choreography (event-driven)](diagrams/svg/choreography_kafka.svg)\n\n### 4) Orchestration (Temporal) across services\n\n![Orchestration (Temporal)](diagrams/svg/orchestration_temporal.svg)\n\n## 🔧 **Microservice Implementation Summary**\n\n### Overview\n\nComprehensive microservice service in `/src/common/microservice/` enables all NestJS microservice protocols and implementations including RPC, Pub/Sub, AMQP, cron scheduling, and streaming.\n\n#### Core Service Files\n\n- **`microservice.service.ts`** - Main service implementing all microservice protocols\n- **`microservice-config.service.ts`** - Configuration management for all transports\n- **`microservice.controller.ts`** - HTTP API endpoints for microservice operations\n- **`microservice.module.ts`** - NestJS module wiring everything together\n- **`example-usage.service.ts`** - Comprehensive examples of service usage\n- **`index.ts`** - Export declarations for clean imports\n- **`README.md`** - Comprehensive documentation\n\n#### Test Files\n\n- **`test/microservice.integration.spec.ts`** - Integration tests with 29 passing test cases\n\n### Microservice Features Implemented\n\n#### Supported Transports\n\n✅ **TCP** - Simple TCP-based communication  \n✅ **Redis** - Redis as message broker  \n✅ **NATS** - NATS messaging system  \n✅ **RabbitMQ (AMQP)** - Advanced Message Queuing Protocol  \n✅ **gRPC** - High-performance RPC framework  \n✅ **Kafka** - Distributed streaming platform (integrated with existing KafkaService)  \n✅ **MQTT** - Lightweight messaging protocol (integrated with existing MqttService)  \n✅ **BullMQ** - Job queue system (integrated with existing BullMQService)\n\n#### Additional Features\n\n✅ **Real-time Streaming** - Server-Sent Events with multiple channels  \n✅ **Cron Scheduling** - Full cron job management with @nestjs/schedule  \n✅ **Health Monitoring** - Automatic health checks for all transports  \n✅ **Circuit Breaker** - Fault tolerance configuration  \n✅ **Retry Logic** - Configurable retry mechanisms  \n✅ **Comprehensive Configuration** - Environment-based configuration for all features\n\n### Microservice API Endpoints\n\n#### Status \u0026 Health\n\n- `GET /microservice/status` - Service status and available transports\n- `GET /microservice/health` - Comprehensive health check\n- `GET /microservice/metrics` - System and service metrics\n- `GET /microservice/config` - Configuration overview\n\n#### Messaging Operations\n\n- `POST /microservice/message` - Send message via any transport\n- `POST /microservice/event` - Emit event via any transport\n- `POST /microservice/kafka/message` - Send Kafka message\n- `POST /microservice/mqtt/message` - Publish MQTT message\n- `POST /microservice/queue/job` - Add job to BullMQ queue\n\n#### Streaming Operations\n\n- `POST /microservice/stream` - Stream data to channel\n- `GET /microservice/stream/channels` - List available channels\n- `GET /microservice/stream/:channel` - Subscribe to stream (SSE)\n- `GET /microservice/status/live` - Live status updates (SSE)\n\n#### Scheduling Operations\n\n- `POST /microservice/cron` - Add cron job\n- `POST /microservice/cron/:name/remove` - Remove cron job\n\n#### Testing\n\n- `POST /microservice/test/:transport` - Test transport connectivity\n\n### Microservice Configuration\n\n#### Environment Variables Added\n\n```bash\n# Microservice Transports\nENABLE_TCP_MICROSERVICE=false\nENABLE_REDIS_MICROSERVICE=true\nENABLE_NATS_MICROSERVICE=false\nENABLE_RABBITMQ_MICROSERVICE=false\nENABLE_KAFKA=true\nENABLE_BULLMQ=true\nENABLE_STREAMING=true\n\n# Transport-specific configurations\nTCP_HOST=localhost\nTCP_PORT=3001\nNATS_SERVERS=nats://localhost:4222\nRABBITMQ_URL=amqp://localhost:5672\nSTREAMING_CHANNELS=user-events,system-metrics,audit-logs,notifications,real-time-data\n\n# Scheduler/Cron configurations\nENABLE_HEALTH_CHECK_CRON=true\nHEALTH_CHECK_CRON=*/30 * * * *\nENABLE_METRICS_COLLECTION_CRON=false\nMETRICS_COLLECTION_CRON=*/5 * * * *\n\n# Plus many more detailed configuration options...\n```\n\n### Microservice Integration\n\n#### Module Integration\n\n- Added `MicroserviceModule` to `src/apps/api-gateway/app.module.ts`\n- Added `MicroserviceController` to expose HTTP endpoints\n- Integrated with existing `MessagingModule` and `ProtocolsModule`\n\n#### Dependencies Added\n\n- `@nestjs/schedule` - For cron job management\n- `cron` - For cron expression parsing\n\n### Microservice Usage Examples\n\n#### Programmatic Usage\n\n```typescript\n// Inject the service\nconstructor(private readonly microserviceService: MicroserviceService) {}\n\n// Send messages\nawait microserviceService.sendMessage('redis', 'user.create', userData);\n\n// Stream data\nmicroserviceService.streamData('user-events', eventData);\n\n// Add cron jobs\nmicroserviceService.addCronJob('backup', '0 2 * * *', backupCallback);\n\n// Subscribe to streams\nmicroserviceService.subscribeToStream('notifications').subscribe(msg =\u003e {\n  console.log('Received:', msg);\n});\n```\n\n#### HTTP API Usage\n\n```bash\n# Send a Redis message\ncurl -X POST http://localhost:3000/microservice/message\n  -H \"Content-Type: application/json\"\n  -d '{\"transport\": \"redis\", \"pattern\": \"user.create\", \"data\": {\"name\": \"John\"}}'\n\n# Stream data\ncurl -X POST http://localhost:3000/microservice/stream\n  -H \"Content-Type: application/json\"\n  -d '{\"channel\": \"user-events\", \"data\": {\"event\": \"user_login\"}}'\n\n# Subscribe to stream (SSE)\ncurl http://localhost:3000/microservice/stream/user-events\n```\n\n### Microservice Testing\n\n✅ **29 passing test cases** covering:\n\n- Service initialization and configuration\n- All transport configurations\n- Streaming functionality\n- External service integration (Kafka, BullMQ, MQTT)\n- Service status and health monitoring\n- Cron job management\n- Error handling scenarios\n\n### Microservice Architecture\n\nThe implementation follows a clean layered architecture:\n\n1. **Controller Layer** - HTTP API endpoints with proper error handling\n2. **Service Layer** - Core business logic and transport management\n3. **Configuration Layer** - Environment-based configuration management\n4. **Integration Layer** - Seamless integration with existing services\n\n### Key Benefits\n\n1. **Unified Interface** - Single service to manage all microservice protocols\n2. **Feature Flag Support** - Individual transports can be enabled/disabled\n3. **Production Ready** - Comprehensive error handling, health checks, and monitoring\n4. **Extensible** - Easy to add new transports or features\n5. **Well Tested** - Full test coverage with integration tests\n6. **Documentation** - Comprehensive README and inline documentation\n\n### Next Steps\n\nThe microservice service is ready for production use. To get started:\n\n1. Configure desired transports via environment variables\n2. Start the application: `pnpm start:dev`\n3. Access the API at `http://localhost:3000/microservice/status`\n4. Use the HTTP endpoints or inject the service programmatically\n\nThe implementation provides a solid foundation for building scalable microservice architectures with NestJS.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandreibesleaga%2Fnestjs-mstv","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fandreibesleaga%2Fnestjs-mstv","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandreibesleaga%2Fnestjs-mstv/lists"}