Skip to content

raouf-b-dev/ecommerce-store-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1,009 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

πŸ›’ E-commerce Store API

CI TypeScript NestJS PostgreSQL Redis BullMQ Jest Docker License Node.js Version Coverage

An enterprise-grade NestJS API for an e-commerce store built with Domain-Driven Design, Hexagonal Architecture, and modern best practices.

πŸ“‹ Table of Contents


What Is This?

A production-grade e-commerce API built as a modular monolith with NestJS and TypeScript. The codebase implements Domain-Driven Design (both Strategic and Tactical), Hexagonal Architecture, and the distributed systems patterns that most tutorials skip β€” SAGA orchestration with compensation, strict bounded context isolation via ACL Gateways, Redis-backed idempotency, structured observability, and a full RSA-based auth stack with refresh token rotation and RBAC.

Designed as a reference for how to build enterprise backend systems that are testable, maintainable, and production-ready from day one.


πŸš€ Quick Start

Prerequisites

  • Node.js β‰₯ 22 Β· npm β‰₯ 11 Β· Docker Desktop β‰₯ 28 Β· Git β‰₯ 2.49

Installation

# 1. Clone & install
git clone https://github.com/raouf-b-dev/ecommerce-store-api.git
cd ecommerce-store-api
npm install

# 2. Generate environment files
npm run env:init

# 3. Update .env.* files with your secrets (DB, Redis, JWT keys)

# 4. Start infrastructure & run migrations
npm run d:up:dev
npm run migration:run:dev

# 5. Start the API
npm run start:dev

The API will be available at http://localhost:3000 πŸŽ‰

πŸ“‘ API Documentation β€” full endpoint specs, schemas, and auth requirements via Swagger UI: http://localhost:3000/api

Optional: Start the Full Monitoring Stack

# Start API + PostgreSQL + Redis + Prometheus + Loki + Tempo + Grafana
npm run d:up:full:prod

Grafana dashboards will be available at http://localhost:3000 (Grafana port) with pre-provisioned datasources and dashboards.


Architecture at a Glance

graph TD
    Client["πŸ“± Client App (Web/Mobile)"] -->|HTTP/REST| API["πŸ›‘οΈ NestJS API Gateway"]
    Client -->|WebSocket| WS["πŸ”Œ WebSocket Gateway"]

    subgraph "Application Core (Modular Monolith)"
        API --> Auth["πŸ” Auth Module"]
        API --> Orders["πŸ“¦ Orders Module"]
        API --> Products["🏷️ Products Module"]
        API --> Carts["πŸ›’ Carts Module"]
        API --> Payments["πŸ’³ Payments Module"]
        API --> Inventory["🏭 Inventory Module"]
        API --> Customers["πŸ‘₯ Customers Module"]

        WS --> Notifications["πŸ”” Notifications Module"]

        Orders -->|SAGA Orchestration| Inventory
        Orders -->|SAGA Orchestration| Payments
        Orders -->|Event| Notifications
    end

    subgraph "Infrastructure Layer"
        Auth -->|Persist| PG["🐘 PostgreSQL"]
        Orders -->|Persist| PG
        Products -->|Persist| PG

        Carts -->|Cache/Persist| Redis["⚑ Redis Stack"]
        Products -->|Search| Redis

        Orders -->|Async Jobs| BullMQ["πŸ‚ BullMQ Job Queue"]
        Notifications -->|Async Jobs| BullMQ
    end

    subgraph "Observability Layer"
        API -->|Structured Logs| Loki["πŸ“‹ Loki"]
        API -->|Metrics /metrics| Prometheus["πŸ“Š Prometheus"]
        API -->|Traces OTLP| Tempo["πŸ” Tempo"]
        Loki --> Grafana["πŸ“ˆ Grafana"]
        Prometheus --> Grafana
        Tempo --> Grafana
    end

    subgraph "External Services"
        Payments <-->|Verify| Stripe["πŸ’³ Payment Gateway"]
    end
Loading

See the full System Architecture & Diagrams for C4, sequence, and class diagrams.


⭐ Feature Catalog

Every feature links to detailed documentation in docs/FEATURES.md and/or the relevant source code.

πŸ—οΈ Architecture

Feature Description Location
Strategic DDD Subdomains, Bounded Contexts, Context Mapping ARCHITECTURE.md
Tactical DDD Entities, Value Objects, Aggregates, Domain Services src/modules/*/core/domain/
Hexagonal Architecture Ports & Adapters β€” infrastructure-agnostic domain core DDD-HEXAGONAL.md
ACL Gateway Pattern 7 gateway ports decoupling 8 bounded contexts INTEGRATION-PATTERNS.md
Modular Monolith 9 isolated modules, microservice-extraction ready src/modules/
Result Pattern Functional Result<T, E> replacing exception-driven flow src/shared-kernel/domain/

πŸ”„ Distributed Systems

Feature Description Location
SAGA Orchestration Multi-step checkout with automatic compensation on failure src/modules/orders/primary-adapters/jobs/
Idempotency Redis-backed @Idempotent() decorator β€” execute-exactly-once src/infrastructure/idempotency/
BullMQ Nested Flows Composed background job pipelines for notifications src/modules/notifications/
Hybrid Payment Strategy Unified COD + Online checkout via Strategy Pattern src/modules/payments/

⚑ Data & Performance

Feature Description Location
RedisJSON Cart storage as native JSON documents β€” no SQL joins src/modules/carts/secondary-adapters/
RedisSearch Full-text search and filtering from Redis src/modules/products/secondary-adapters/
Cache-Aside Decorator Transparent CachedRepository wrapping Postgres with Redis src/modules/*/secondary-adapters/repositories/cached-*/

πŸ” Security

Feature Description Location
RSA JWT (RS256 + JWKS) Production-grade auth with public key distribution endpoint JWT-RSA-JWKS.md
Refresh Token Rotation Session-based tokens with SHA-256 hashing + HttpOnly cookies src/modules/auth/
RBAC System Database-backed Roles & Permissions with PermissionsGuard src/modules/auth/core/domain/
API Rate Limiting Redis-backed throttling via @nestjs/throttler src/infrastructure/throttler/
Helmet Headers Standard security headers (HSTS, X-Frame-Options, etc.) src/main.ts
CORS Whitelist Environment-based origin restriction β€” no wildcards in prod src/config/
XSS Sanitization Global sanitize-html interceptor on all request bodies src/interceptors/
Pagination Safety @Max(100) on all query DTOs to prevent resource exhaustion src/modules/*/primary-adapters/dtos/

πŸ“¦ Infrastructure

Feature Description Location
Multi-Stage Docker 4-stage build, Node.js 24 Alpine, tini PID 1, non-root user Dockerfile
Graceful Shutdown Signal handling, connection draining, worker cleanup PROCESS-LIFECYCLE.md
Health Checks GET /health via @nestjs/terminus (Postgres + Redis + WS) src/modules/health/
API Versioning URI-based versioning (/v1/) for all API endpoints src/modules/*/
Admin Seeder Bootstrap admin user and role/permission data on first deploy ADMIN-BOOTSTRAP.md
Multi-Env Config 4 profiles with type-safe validation + secrets separation SECRETS-MANAGEMENT.md

πŸ”­ Observability

Feature Description Location
Structured Logging Winston JSON logging shipped to Loki via Promtail src/infrastructure/logging/
Correlation IDs X-Request-Id propagated through HTTP + all 18 BullMQ jobs src/infrastructure/logging/
Prometheus Metrics RED method metrics + business telemetry via prom-client src/infrastructure/metrics/
Distributed Tracing OpenTelemetry auto-instrumentation exporting to Tempo via OTLP gRPC src/infrastructure/tracing/
Grafana Stack Pre-provisioned dashboards with Loki, Prometheus, and Tempo datasources MONITORING-STACK-GUIDE.md
Domain Event Metrics Business events (login, order, payment) published and tracked src/infrastructure/metrics/listeners/
CI/CD Pipeline GitHub Actions: lint β†’ build β†’ test β†’ publish .github/workflows/

πŸ§ͺ Testing

Feature Description Location
Unit + Integration Suite Domain logic, use cases, repositories, controllers src/modules/*/
Test Factories Scenario-specific domain object builders per module src/modules/*/testing/
Typed Mock Repos Interface-compliant mocks with test helper methods src/modules/*/testing/

πŸ“– Documentation Index

Document Description
FEATURES.md Detailed feature documentation with code locations
docs/README.md Unified technical documentation index
ARCHITECTURE.md C4 system context, domain flows, sequence diagrams
DDD-HEXAGONAL.md Canonical DDD & Hexagonal Architecture rules
INTEGRATION-PATTERNS.md ACL Gateway, SAGA, Domain Events, Outbox
JWT-RSA-JWKS.md RSA JWT implementation and JWKS endpoint details
SECRETS-MANAGEMENT.md Configuration taxonomy and key rotation
ADMIN-BOOTSTRAP.md Admin seeding, role/permission initialization
MONITORING-STACK-GUIDE.md Grafana, Prometheus, Loki, Tempo setup and usage
Observability Architecture Signal pipeline diagram (logs, metrics, traces β†’ Grafana)
PROCESS-LIFECYCLE.md PIDs, signals, and graceful shutdown deep-dive
ROADMAP.md Production readiness checklist with prioritized tasks
TROUBLESHOOTING.md Common issues and solutions
AGENT.md Coding guidelines and conventions

🚧 Roadmap

This project is continuously evolving. See the full ROADMAP.md for completed phases, current work, and upcoming features.


πŸ§ͺ Testing

npm test              # Run all unit tests
npm run test:cov      # Generate coverage report
npm run test:e2e      # End-to-end tests
npm run test:ci       # CI mode (GitHub Actions)

πŸ—οΈ Project Structure

src/
β”œβ”€β”€ shared-kernel/           # Pure domain building blocks (Result, Value Objects, base UseCase)
β”œβ”€β”€ infrastructure/          # Global secondary adapters (DB, Redis, BullMQ, JWT, logging, WebSocket)
β”œβ”€β”€ interceptors/            # Global Result Interceptor
β”œβ”€β”€ modules/                 # Feature Modules (Bounded Contexts)
β”‚   └── [module]/
β”‚       β”œβ”€β”€ core/domain/     # Entities, Value Objects, Repository Ports
β”‚       β”œβ”€β”€ core/application/# Use Cases & Application Services
β”‚       β”œβ”€β”€ primary-adapters/# DTOs, Controllers, Job Handlers, Listeners
β”‚       β”œβ”€β”€ secondary-adapters/# Repositories, Gateways, Schedulers
β”‚       └── testing/         # Module-specific mocks & factories
β”œβ”€β”€ config/                  # Environment validation & configuration
└── main.ts                  # Application bootstrap

For strict DDD and Hexagonal Architecture definitions, see DDD-HEXAGONAL.md.


πŸ“„ License

Released under the MIT License.


Built by Abderaouf .B Β· Issues Β· Repository

About

A production-grade NestJS modular monolith E-commerce API πŸ›’. Built as a reference implementation demonstrating Domain-Driven Design (DDD), Hexagonal Architecture, and SAGA orchestration.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages