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.
- 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-managerandcache-managerfor memory caching and automated cache invalidation on catalog mutations. - Monitoring & Metrics: Prometheus metric exporter (
@willsoto/nestjs-prometheus,prom-client) exposingGET /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 windowRateLimiterGuard - 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
# 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- URL:
http://localhost:3000/api/docs - Features interactive endpoint testing, parameter schemas, DTO models, and Bearer / API Key authentication headers.
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: requiresAuthorization: Bearer <token>).
GET /audit/logs- Fetch domain event audit log history (Protected: requires JWT Bearer Token &@Roles('admin')).
GET /notifications/history- Fetch transactional email notification delivery logs (Protected: requires JWT Bearer Token &@Roles('admin')).
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).
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 }).
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.
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: requiresx-api-keyheader).POST /products/admin- Create new product (Protected: requires JWT Bearer Token &@Roles('admin')).PATCH /products/:id- Update existing product (Protected: requiresx-api-keyheader).DELETE /products/:id- Remove product from catalog (Protected: requiresx-api-keyheader).
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.
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: requiresx-api-keyheader).
| 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 |
# Development server (with hot reload)
npm run start:dev
# Production compilation
npm run build
# Production start
npm start# Run unit and e2e integration test suite
npm test
# Run test coverage report
npm run test:cov- 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-keyauthorization headers.
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"
}- Managed by
RateLimiterGuardenforcing a sliding window rate limit of 30 requests per minute per IP address. - Exceeding the rate limit returns an
HTTP 429 Too Many Requestsstatus code.
This API was engineered to showcase NestJS's opinionated architecture and dependency injection system:
- Modular Architecture: Features are domain-isolated into NestJS modules (
ProductsModule,HealthModule,CommonModule). - Dependency Injection: Services (
ProductsService) are decorated with@Injectable()and injected into controllers via constructor injection, decoupling business logic from HTTP routing. - Execution Guards:
ApiKeyGuardleverages NestJS'sCanActivateandExecutionContextto validatex-api-keyheaders before protected routes (POST,PATCH,DELETE) execute. - 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: ... }.
- DTO Validation Pipes: Request bodies are validated at boundary level using NestJS
ValidationPipecombined withclass-validatordecorators.
- 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.