A robust, enterprise-grade Node.js/TypeScript service for managing rules engine and workflow automation with comprehensive authentication, authorization, and multi-database support.
The Workflow Service is a microservice designed to handle complex business rules and conditional logic through a sophisticated rules engine. It provides a RESTful API for creating, managing, and executing rules and conditions with fine-grained access control and comprehensive monitoring capabilities.
- Rules Engine: Create and manage complex business rules with conditions and operators
- Multi-Database Support: PostgreSQL and MySQL database support with TypeORM
- Authentication & Authorization: Only data access routes are protected by JWT-based authentication with role-based access control (RBAC). Webhooks and internal APIs use respective channel tokens.
- Multi-Tenancy: Built-in tenant isolation and management
- Cloud-Native: Docker support with AWS S3 integration for file storage
- Observability: OpenTelemetry instrumentation with multiple logging providers
- Microservice Architecture: Modular design with dependency injection
- Production Ready: Comprehensive error handling, rate limiting, and graceful shutdown
- Prerequisites
- Installation
- Configuration
- Environment Variables
- Database Setup
- API Documentation
- Authentication
- Authorization
- Architecture
- Deployment
- Monitoring
- Development
- Contributing
- Node.js: 22.x or higher
- npm: 11.0 or higher
- Database: PostgreSQL 12+ or MySQL 8.0+
- Docker (optional): For containerized deployment
- AWS Account (optional): For S3 file storage and secret management
# Clone the repository
git clone <repository-url>
cd service-template-skeleton
# Install dependencies
npm install
# Create environment file
cp .env.example .env
# Build the project
npm run build
# Start development server
npm run dev# Build Docker image
docker build -t rean-bot-service .
# Run container
docker run -p 3000:3000 rean-bot-serviceThe service uses a layered configuration approach:
- Default Configuration:
service.config.json - Environment Variables: Override defaults
- Local Configuration:
service.config.local.json(optional)
{
"SystemIdentifier": "ReanBot",
"BaseUrl": "https://localhost:7373",
"Logging": {
"Provider": "Custom",
"Level": "Information"
},
"FileStorage": {
"Provider": "AWS-S3"
},
"Email": {
"Provider": "SendGrid"
},
"Sms": {
"Provider": "Twilio"
},
"MaxUploadFileSize": 104857600,
"Telemetry": false
}# Service Configuration
SERVICE_NAME=rean-bot-service
NODE_ENV=development
PORT=7373
BASE_URL=http://localhost:7373
# Database Configuration
DB_DIALECT=mysql # or postgres
DB_HOST=localhost
DB_PORT=3306
DB_NAME=rean_bot_db
DB_USER_NAME=username
DB_USER_PASSWORD=password
# Authentication
USER_ACCESS_TOKEN_SECRET=your-jwt-secret
INTERNAL_API_KEY=your-internal-api-key
USER_SERVICE_BASE_URL=http://localhost:7171
# External Services
S3_CONFIG_BUCKET=your-config-bucket
S3_CONFIG_PATH=config/path
# Logging & Monitoring
HTTP_LOGGING=true
ENABLE_TELEMETRY=false
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://localhost:4317
# File Storage (AWS S3)
AWS_ACCESS_KEY_ID=your-access-key
AWS_SECRET_ACCESS_KEY=your-secret-key
AWS_REGION=us-west-2
AWS_S3_BUCKET=your-file-bucket
# Email (SendGrid)
SENDGRID_API_KEY=your-sendgrid-key
# SMS (Twilio)
TWILIO_ACCOUNT_SID=your-twilio-sid
TWILIO_AUTH_TOKEN=your-twilio-token- PostgreSQL
- MySQL (Recommended)
The service automatically handles:
- Database Connection: Automatic connection pooling and health checks
- Seeding: Master data
- Test Data: Optional test data seeding for development
// PostgreSQL
DB_DIALECT=postgres
DB_HOST=localhost
DB_PORT=5432
// MySQL
DB_DIALECT=mysql
DB_HOST=localhost
DB_PORT=3306http://localhost:7373/api/v1
GET /api/v1/health-check// Standard Response Format
{
"Status": "success",
"Message": "Operation completed successfully",
"HttpCode": 200,
"Data": {
// Response data
}
}
// Error Response Format
{
"Status": "failure",
"Message": "Error description",
"HttpCode": 400,
"Data": null
}- Client Authentication: API key validation for service-to-service communication
- User Authentication: JWT token validation for user requests
- Session Management: Session-based token validation with expiry
# User Authentication
Authorization: Bearer <jwt-token>
# Client Authentication
x-api-key: <api-key>- Admin: Full system access
- ContentModerator: Rule and condition management
Permissions are structured as Resource.Action:
// Examples
"Rule.Create"
"Rule.GetById"
"Rule.Update"
"Rule.Delete"
"Condition.Create"
"Condition.Search"Each endpoint is protected with context-based authorization:
router.post('/', context('Rule.Create'), controller.create);
router.get('/:id', context('Rule.GetById'), controller.getById);src/
βββ api/ # REST API endpoints
β βββ condition/ # Condition management
β βββ rule/ # Rule management
β βββ types/ # Type definitions
βββ auth/ # Authentication & Authorization
βββ common/ # Shared utilities
βββ config/ # Configuration management
βββ database/ # Database layer
β βββ db.clients/ # Database connectors
β βββ models/ # Data models
β βββ services/ # Business logic
β βββ mappers/ # Data mapping
βββ domain.types/ # Domain type definitions
βββ logger/ # Logging providers
βββ modules/ # External integrations
β βββ email/ # Email services
β βββ sms/ # SMS services
β βββ storage/ # File storage
βββ startup/ # Application bootstrap
βββ telemetry/ # Observability
- Dependency Injection: Using
tsyringefor IoC - Repository Pattern: Data access abstraction
- Service Layer: Business logic separation
- Middleware Pattern: Request/response processing
- Observer Pattern: Event handling and logging
# Build image
docker build -t rean-bot-service:latest .
# Run with environment variables
docker run -d \
--name rean-bot-service \
-p 3000:3000 \
--env-file .env \
rean-bot-service:latest# task-definition.json
{
"family": "rean-bot-service",
"taskRoleArn": "arn:aws:iam::account:role/ecsTaskRole",
"executionRoleArn": "arn:aws:iam::account:role/ecsTaskExecutionRole",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "256",
"memory": "512",
"containerDefinitions": [
{
"name": "rean-bot-service",
"image": "rean-bot-service:latest",
"portMappings": [
{
"containerPort": 3000,
"protocol": "tcp"
}
],
"environment": [
{
"name": "NODE_ENV",
"value": "production"
}
]
}
]
}- Environment variables configured
- Database migrations applied
- SSL/TLS certificates configured
- Load balancer configured
- Monitoring and logging enabled
- Health checks configured
- Backup strategy implemented
The service includes comprehensive observability:
// Tracing
import { Trace } from './telemetry/instrumenter';
@Trace('RuleService.create')
async create(rule: RuleCreateModel): Promise<RuleResponseDto> {
// Implementation
}- Custom Logger (Default)
- Winston
- Pino
- Bunyan
# Health Check
GET /api/v1/health-check
# Metrics (if enabled)
GET /metricsERROR: Application errorsWARN: Warning conditionsINFO: General informationDEBUG: Debug information
# Development
npm run dev # Start with nodemon
npm run start # Production start
npm run build # TypeScript compilation
# Code Quality
npm run lint # ESLint check
npm run lint:fix # ESLint fix
npm test # Run tests (when configured)- TypeScript: Strict type checking enabled
- ESLint: Airbnb configuration with custom rules
- Code Structure: Follow domain-driven design principles
- Error Handling: Comprehensive error handling with proper HTTP status codes
- Testing: Unit and integration tests (framework ready)
- Create domain types in
src/domain.types/<module>/ - Implement database model in
src/database/models/<module>/ - Add service layer in
src/database/services/<module>/ - Create API controller, routes, auth options and validators in
src/api/<module>/ - Update permissions in master data
- Add OpenTelemetry instrumentation for tracing
- Write unit tests for new features
- Add Bruno requests for new features
- Update documentation
# Install dependencies
npm install
# Set up pre-commit hooks
npm run prepare
# Run in development mode
npm run dev