Skip to content

kitsune2411/DDD

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

19 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

DDD - Domain Driven Design Application

A scalable Node.js application built with Domain-Driven Design (DDD) principles using Express, MySQL, Redis, and BullMQ for asynchronous job processing.

πŸ“‹ Table of Contents


🎯 Overview

This project demonstrates enterprise-grade Node.js development using Domain-Driven Design, featuring:

βœ… Modular Architecture - Independent, testable business domains
βœ… DDD Patterns - Aggregate Roots, Value Objects, Domain Events
βœ… Async Processing - BullMQ for background jobs (email, reports, etc.)
βœ… Security - Helmet, CORS, Rate Limiting, JWT
βœ… Logging - Winston with daily rotation
βœ… Database - MySQL with Knex migrations
βœ… Docker Ready - Containerized for production


πŸ› οΈ Technology Stack

Layer Technology
Runtime Node.js
Framework Express 5.x
Database MySQL 8 + Knex (Query Builder + Migrations)
ORM/Query Knex.js
Cache/Queue Redis + BullMQ
Email Nodemailer
Security Helmet, CORS, Rate Limiting, bcrypt, JWT
Logging Winston
Testing Jest + Supertest
HTTP Templates Handlebars (for email templates)
Validation Zod

πŸ“ Project Structure

ddd/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config/                 # Configuration files
β”‚   β”‚   └── database.js         # Database connection setup
β”‚   β”‚
β”‚   β”œβ”€β”€ modules/                # Business Domains (Bounded Contexts)
β”‚   β”‚   β”œβ”€β”€ order/              # Order Management Domain
β”‚   β”‚   β”‚   β”œβ”€β”€ domain/         # Business rules (Order entity, events)
β”‚   β”‚   β”‚   β”œβ”€β”€ application/    # Use cases (CreateOrderService)
β”‚   β”‚   β”‚   β”œβ”€β”€ infrastructure/ # Data access (repositories, DB queries)
β”‚   β”‚   β”‚   β”œβ”€β”€ interface/      # API endpoints (HTTP routes, DTOs)
β”‚   β”‚   β”‚   └── workers/        # Background jobs (email, notifications)
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ catalog/            # Product Catalog Domain
β”‚   β”‚   β”‚   β”œβ”€β”€ domain/         # Catalog aggregate, value objects
β”‚   β”‚   β”‚   β”œβ”€β”€ application/    # Queries and use-cases (GetCatalogList, CreateCatalog)
β”‚   β”‚   β”‚   β”œβ”€β”€ infrastructure/ # Persistence adapters (MySQLCatalogRepository)
β”‚   β”‚   β”‚   β”œβ”€β”€ interface/      # HTTP routes, DTOs, controllers
β”‚   β”‚   β”‚   └── mapper/         # Mapping between domain and DTOs
β”‚   β”‚   β”‚
β”‚   β”‚   └── partner/            # Partner/Vendor Domain
β”‚   β”‚       β”œβ”€β”€ domain/
β”‚   β”‚       β”œβ”€β”€ application/
β”‚   β”‚       β”œβ”€β”€ infrastructure/
β”‚   β”‚       └── interface/
β”‚   β”‚
β”‚   └── shared/                 # Shared utilities & infrastructure
β”‚       β”œβ”€β”€ core/               # Base classes & error handling
β”‚       β”‚   β”œβ”€β”€ AggregateRoot.js
β”‚       β”‚   β”œβ”€β”€ AppError.js
β”‚       β”‚   β”œβ”€β”€ Guard.js
β”‚       β”‚   └── ValueObject.js
β”‚       β”‚
β”‚       β”œβ”€β”€ infra/              # Shared infrastructure
β”‚       β”‚   β”œβ”€β”€ database/       # MySQL connection (Singleton)
β”‚       β”‚   β”œβ”€β”€ email/          # Email service + templates
β”‚       β”‚   β”œβ”€β”€ http/           # Middleware, error handler
β”‚       β”‚   β”œβ”€β”€ logging/        # Winston logger
β”‚       β”‚   └── queue/          # BullMQ queue factory
β”‚       β”‚
β”‚       └── utils/              # Helper functions
β”‚           β”œβ”€β”€ DateUtils.js
β”‚           β”œβ”€β”€ ObjectUtils.js
β”‚           β”œβ”€β”€ PaginationUtils.js
β”‚           └── TextUtils.js
β”‚
β”œβ”€β”€ migrations/                 # Database migration files (Knex)
β”œβ”€β”€ docker-compose.yml          # Multi-container setup (App, MySQL, Redis)
β”œβ”€β”€ Dockerfile                  # Container image definition
β”œβ”€β”€ Makefile                    # Development commands
β”œβ”€β”€ knexfile.js                 # Knex configuration
β”œβ”€β”€ server.js                   # Application entry point
└── package.json                # Dependencies

πŸš€ Getting Started

Prerequisites

  • Node.js 16+ (or higher)
  • npm or yarn
  • MySQL 8+ (or Docker)
  • Redis (or Docker)

Installation

  1. Clone the repository

    git clone <repository>
    cd ddd
  2. Install dependencies

    npm install
    # or use Makefile
    make install
  3. Create environment file

    cp .env.example .env
  4. Configure .env file

    NODE_ENV=development
    PORT=3000
    
    # Database
    DB_HOST=localhost
    DB_USER=root
    DB_PASSWORD=password
    DB_NAME=ddd_db
    DB_PORT=3306
    
    # Redis
    REDIS_HOST=localhost
    REDIS_PORT=6379
    
    # Email
    SMTP_HOST=smtp.gmail.com
    SMTP_PORT=587
    SMTP_USER=your-email@gmail.com
    SMTP_PASS=your-app-password
    
    # JWT
    JWT_SECRET=your-secret-key
    JWT_EXPIRY=7d
  5. Run database migrations

    npm run migrate:latest
    # or
    make migrate-up
  6. Start the server

    npm run dev
    # or
    make dev

    Server will run on http://localhost:3000


πŸ“ Development

Common Commands

Command Purpose
make dev Run server in watch mode (Nodemon)
make start Run server in production mode
make test Run test suite (Jest)
make module name=payment Generate new DDD module scaffold
make migrate-make name=create_users Create new database migration
make migrate-up Run pending migrations
make migrate-down Rollback last migration
make help Show all available commands

Project Aliases

The project uses module-alias for clean imports:

// Instead of: require('../../../shared/core')
// You write:
const { AggregateRoot, Guard } = require("@shared/core");
const orderModule = require("@modules/order");

Alias mapping (in package.json):

{
  "_moduleAliases": {
    "@shared": "src/shared",
    "@modules": "src/modules",
    "@config": "src/config"
  }
}

🐳 Docker Deployment

Quick Start with Docker

# Build and start all services (App, MySQL, Redis)
make docker-up

# Stop services
make docker-down

# Rebuild and restart
make docker-update

# Scale app to 3 instances
make docker-scale n=3

Docker Services

docker-compose.yml includes:

  • app - Node.js application (Port 3000)
  • mysql - MySQL database (Port 3306)
  • redis - Redis cache (Port 6379)

πŸ—„οΈ Database Migrations

All database changes go through migrations for version control and reproducibility.

Create Migration

make migrate-make name=create_orders_table

This creates a file in migrations/ like:

exports.up = function (knex) {
  return knex.schema.createTable("orders", (table) => {
    table.uuid("id").primary();
    table.uuid("customer_id").notNullable();
    table.decimal("total", 10, 2);
    table.enum("status", ["PENDING", "PAID", "CANCELLED"]);
    table.timestamps(true, true);
  });
};

exports.down = function (knex) {
  return knex.schema.dropTableIfExists("orders");
};

Run Migrations

# Run all pending migrations
make migrate-up

# Rollback last batch
make migrate-down

# Rollback all migrations
make migrate-rollback

# Check status
make db-status

πŸ“š API Documentation

Detailed API endpoints are documented in API_DOCUMENTATION.md.

Health Check

curl http://localhost:3000/health

Response:

{
  "status": "OK",
  "uptime": 123.456,
  "db": "Connected"
}

Order Endpoints

# Create order
POST /api/orders
Content-Type: application/json

{
  "customerId": "uuid-here",
  "items": [
    { "productId": "prod-1", "quantity": 2, "price": 50.00 }
  ],
  "email": "customer@example.com"
}

πŸ—οΈ Architecture

This project follows Domain-Driven Design (DDD) principles. See ARCHITECTURE.md for detailed explanation of:

  • Bounded Contexts - Isolated business domains
  • Aggregates - Consistency boundaries
  • Domain Events - Domain-driven communication
  • Repository Pattern - Data access abstraction
  • Service Layer - Business logic orchestration
  • Value Objects - Immutable concepts
  • DTOs - Data transfer objects

πŸ”’ Security Features

βœ… Helmet - HTTP security headers
βœ… CORS - Cross-origin resource sharing control
βœ… Rate Limiting - Anti-DDoS protection (100 req/15min per IP)
βœ… bcrypt - Password hashing
βœ… JWT - Token-based authentication
βœ… Input Validation - Zod schema validation
βœ… Error Handling - No stack traces exposed to clients


πŸ“Š Logging

Winston logger configured with:

  • Console output (development)
  • File rotation (daily logs in logs/ directory)
  • Request tracking (HTTP method, URL, duration)
  • Error logging (stack traces in files, messages to client)

πŸ§ͺ Testing

# Run tests
make test

# Watch mode
make test-watch

Uses Jest + Supertest for unit and integration tests.


🚨 Troubleshooting

"Cannot find module '@shared/core'"

Solution: Ensure module-alias/register is loaded first in server.js

"MySQL Connection Refused"

Solution: Check DB_HOST, DB_USER, DB_PASSWORD in .env

# Test MySQL connection
mysql -h localhost -u root -p

"Redis Connection Refused"

Solution: Start Redis service

# macOS
brew services start redis

# Linux
sudo systemctl start redis-server

# Docker
docker-compose up -d redis

Background Jobs Not Processing

Solution: Ensure Redis is running and BullMQ workers are initialized in server.js


πŸ“– Documentation Files


🀝 Contributing

  1. Create a new branch: git checkout -b feature/my-feature
  2. Follow DDD structure when adding features
  3. Write tests for business logic
  4. Submit a pull request

πŸ“„ License

ISC License


πŸ“ž Support

For issues or questions, please check:

  1. Troubleshooting section
  2. ARCHITECTURE.md for design patterns
  3. API_DOCUMENTATION.md for API usage

Last Updated: December 28, 2025
Version: 1.0.0

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors