Skip to content

Repository files navigation

Build 60: NestJS E-Commerce REST API

Continuous Integration

An enterprise-grade RESTful E-Commerce Catalog API built with Node.js and NestJS, highlighting fundamental NestJS architectural patterns including custom Feature Modules, Controllers, Services, Dependency Injection (DI), Execution Guards, Response Interceptors, DTO Input Validation Pipes, and GitHub Actions CI.

Stack

  • Core: Node.js NestJS (TypeScript, Dependency Injection, Modules, Controllers, Services)
  • ORM & Database Layer: TypeORM (@nestjs/typeorm) with SQLite relational database (data/ecommerce.sqlite).
  • Distributed Caching: @nestjs/cache-manager and cache-manager for memory caching and automated cache invalidation on catalog mutations.
  • Monitoring & Metrics: Prometheus metric exporter (@willsoto/nestjs-prometheus, prom-client) exposing GET /metrics.
  • Authentication: JWT Bearer Tokens (HMAC-SHA256), Custom @Roles() decorator, JwtAuthGuard, RolesGuard (RBAC)
  • API Documentation: OpenAPI v3 & Interactive Swagger UI (/api/docs)
  • Event-Driven Architecture: @nestjs/event-emitter (order.created, order.cancelled, product.created)
  • Validation: class-validator, class-transformer
  • Error Handling & Protection: Global HttpExceptionFilter, sliding window RateLimiterGuard
  • Testing: Jest (Unit & Integration tests), Supertest (e2e API testing)
  • CI/CD: GitHub Actions CI (ubuntu-latest, Node.js 18.x & 20.x matrix)
  • Package Manager: npm

Setup

# Clone repository
git clone https://github.com/breakingthebot/ecommerce-api-build60.git
cd ecommerce-api-build60

# Install dependencies
npm install

# Configure environment variables
cp .env.example .env

Endpoints

Interactive API Documentation (Swagger / OpenAPI)

  • URL: http://localhost:3000/api/docs
  • Features interactive endpoint testing, parameter schemas, DTO models, and Bearer / API Key authentication headers.

Authentication & User Management (/auth)

  • POST /auth/register - Register a new customer or admin account ({ email, password, name, role }).
  • POST /auth/login - Authenticate user credentials and return a signed JWT Bearer Token.
  • GET /auth/me - Fetch authenticated user profile (Protected: requires Authorization: Bearer <token>).

Audit Trail (/audit)

  • GET /audit/logs - Fetch domain event audit log history (Protected: requires JWT Bearer Token & @Roles('admin')).

Transactional Notifications (/notifications)

  • GET /notifications/history - Fetch transactional email notification delivery logs (Protected: requires JWT Bearer Token & @Roles('admin')).

Customer Wishlist & Favorites (/wishlist)

  • GET /wishlist - Fetch current user's saved wishlist favorites (Protected: requires JWT Bearer Token).
  • POST /wishlist/items - Add product item to saved wishlist ({ productId }) (Protected: requires JWT Bearer Token).
  • DELETE /wishlist/items/:productId - Remove product from wishlist (Protected: requires JWT Bearer Token).
  • POST /wishlist/items/:productId/move-to-cart/:cartId - Transfer item directly from wishlist into active shopping cart (Protected: requires JWT Bearer Token).

Promotional Discounts (/discounts)

  • GET /discounts - List all active promotional discount codes.
  • POST /discounts - Create new promo code (Protected: requires JWT Bearer Token & @Roles('admin')).
  • POST /discounts/validate - Validate promo code against cart subtotal ({ code, orderTotal }).

Prometheus Metrics & Health Diagnostics

  • GET /metrics - Prometheus metrics scraping exposition endpoint (http_requests_total, http_request_duration_seconds, process memory, CPU utilization).
  • GET /health - System health diagnostic status and uptime.

Product Catalog & Search (/products)

  • GET /products - Fetch all products (optional query parameters: category, tag).
  • GET /products/search - Advanced search, multi-field filtering (q, category, tag, minPrice, maxPrice), sorting, and pagination.
  • GET /products/:id - Fetch single product by ID.
  • GET /products/:id/reviews - Fetch product reviews and calculated average star rating score.
  • POST /products/:id/reviews - Submit product review & 1-5 star rating ({ rating, comment }) (Protected: requires JWT Bearer Token).
  • POST /products - Create new product (Protected: requires x-api-key header).
  • POST /products/admin - Create new product (Protected: requires JWT Bearer Token & @Roles('admin')).
  • PATCH /products/:id - Update existing product (Protected: requires x-api-key header).
  • DELETE /products/:id - Remove product from catalog (Protected: requires x-api-key header).

Shopping Cart (/cart)

  • GET /cart/:cartId - Get shopping cart items and totals.
  • POST /cart/:cartId/items - Add item to cart ({ productId, quantity }).
  • PATCH /cart/:cartId/items/:productId - Update item quantity ({ quantity }).
  • DELETE /cart/:cartId/items/:productId - Remove item from cart.
  • DELETE /cart/:cartId - Clear all items from cart.

Order Processing (/orders)

  • POST /orders - Place order from cart ({ cartId, customerEmail }), reserve stock, and clear cart.
  • GET /orders - Fetch list of all orders.
  • GET /orders/:id - Fetch single order details by ID.
  • PATCH /orders/:id/status - Transition order status ({ status }: PENDING, PAID, SHIPPED, DELIVERED, CANCELLED). (Protected: requires x-api-key header).

Environment Variables

Variable Description Default
PORT HTTP server port 3000
NODE_ENV Environment mode (development, test, production) development
API_KEY Secret API Key for securing write routes (x-api-key header) secret-api-key-123

Running Locally

# Development server (with hot reload)
npm run start:dev

# Production compilation
npm run build

# Production start
npm start

Running Tests

# Run unit and e2e integration test suite
npm test

# Run test coverage report
npm run test:cov

Data Handling

  • Data Retention: Zero persistent external database required. All catalog items, prices, and stock counts are held in-memory during application execution.
  • Privacy & Security: Zero personal data or credentials are logged or retained. Sensitive requests require standard x-api-key authorization headers.

Error Handling & Rate Limiting

Standard Error Response Envelope

All application errors and exceptions are intercepted by HttpExceptionFilter to produce a consistent JSON envelope:

{
  "success": false,
  "statusCode": 404,
  "error": "NotFoundException",
  "message": "Product with ID 'PROD-9999' was not found.",
  "path": "/products/PROD-9999",
  "method": "GET",
  "timestamp": "2026-08-02T15:57:00.000Z"
}

Rate Limiting Protection

  • Managed by RateLimiterGuard enforcing a sliding window rate limit of 30 requests per minute per IP address.
  • Exceeding the rate limit returns an HTTP 429 Too Many Requests status code.

Architecture Notes

This API was engineered to showcase NestJS's opinionated architecture and dependency injection system:

  1. Modular Architecture: Features are domain-isolated into NestJS modules (ProductsModule, HealthModule, CommonModule).
  2. Dependency Injection: Services (ProductsService) are decorated with @Injectable() and injected into controllers via constructor injection, decoupling business logic from HTTP routing.
  3. Execution Guards: ApiKeyGuard leverages NestJS's CanActivate and ExecutionContext to validate x-api-key headers before protected routes (POST, PATCH, DELETE) execute.
  4. Interceptors: Global interceptors inspect and mutate execution flows:
    • LoggingInterceptor: Measures request processing time in milliseconds.
    • TransformInterceptor: Envelopes all JSON responses into a consistent schema { success: true, data: ..., timestamp: ... }.
  5. DTO Validation Pipes: Request bodies are validated at boundary level using NestJS ValidationPipe combined with class-validator decorators.

Notes & Known Limitations

  • Catalog storage is currently in-memory. Restarting the server resets inventory to initial seeded records.
  • Next iterations will add persistent ORM database layers (e.g. TypeORM or Prisma) and shopping cart / checkout workflows.

About

Enterprise NestJS E-Commerce REST API showcasing modules, controllers, services, guards, interceptors, and full dependency injection pattern.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages