Skip to content

lab-kolerr/Node.js-Express-HITL-test_v8

Repository files navigation

E-Commerce REST API

A production-ready, scalable e-commerce REST API built with Node.js, Express, PostgreSQL, and Redis. This API provides comprehensive features for managing products, users, orders, payments, and more with enterprise-grade security and performance optimizations.

📋 Table of Contents

🎯 Project Description

This e-commerce REST API is designed to power modern online stores with a robust, scalable backend infrastructure. Built following industry best practices, it implements modular architecture, comprehensive security measures, and optimized performance for handling high-traffic production environments.

Key Highlights:

  • Production-ready with Docker containerization
  • Secure authentication with JWT and refresh tokens
  • Integrated payment processing via Stripe
  • Advanced caching with Redis
  • Full-text search capabilities
  • Role-based access control (RBAC)
  • Comprehensive API documentation with Swagger
  • Extensive test coverage with Jest

✨ Features

1. User Authentication & Authorization

  • User registration with email verification
  • Secure login/logout with JWT tokens
  • Refresh token rotation for enhanced security
  • Password hashing with bcrypt (configurable rounds)
  • Rate limiting to prevent brute-force attacks
  • Role-based access control (Admin, User, Guest)

2. Product Catalog Management

  • Full CRUD operations for products
  • Hierarchical category management
  • Advanced search with full-text capabilities
  • Multi-field filtering and sorting
  • Inventory tracking with low stock alerts
  • Image upload to AWS S3
  • Product variants and SKU management

3. Shopping Cart

  • Add, update, and remove items
  • Real-time price calculations
  • Session management with Redis
  • Cart persistence for authenticated users
  • Product recommendations based on cart contents

4. Order Processing

  • Secure order creation from cart
  • Multi-status order tracking (Pending, Processing, Shipped, Delivered, Cancelled)
  • Stripe payment integration with webhooks
  • Order history with pagination
  • Email notifications for order updates
  • Invoice generation

5. Admin Dashboard

  • Product management (bulk import/export)
  • Order management and fulfillment
  • User management and role assignment
  • Sales analytics and reporting
  • Inventory monitoring
  • System health metrics

6. Additional Features

  • Comprehensive logging with Winston
  • Error handling middleware
  • Input validation and sanitization
  • XSS and SQL injection prevention
  • CORS configuration
  • API rate limiting
  • Database connection pooling
  • Asynchronous job processing

📦 Prerequisites

Before installing, ensure you have the following installed:

  • Node.js: v20.x or higher
  • npm: v10.x or higher
  • PostgreSQL: v14.x or higher
  • Redis: v7.x or higher
  • Docker & Docker Compose: (Optional, for containerized deployment)
  • AWS Account: For S3 storage (or alternative cloud storage)
  • Stripe Account: For payment processing

🚀 Installation

1. Clone the Repository

git clone https://github.com/yourusername/node_express_20251104_121321.git
cd node_express_20251104_121321

2. Install Dependencies

npm install

3. Setup Database

# Create PostgreSQL database
createdb ecommerce_db

# Run migrations
npm run migrate

# Seed initial data (optional)
npm run seed

4. Setup Redis

# Start Redis server (if not running)
redis-server

# Or using Docker
docker run -d -p 6379:6379 redis:7-alpine

⚙️ Configuration

Environment Variables

Create a .env file in the root directory:

# Application
NODE_ENV=development
PORT=3000
API_VERSION=v1

# Database
DB_HOST=localhost
DB_PORT=5432
DB_NAME=ecommerce_db
DB_USER=postgres
DB_PASSWORD=your_password
DB_POOL_MAX=20
DB_POOL_MIN=5

# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0

# JWT
JWT_SECRET=your_jwt_secret_key_here
JWT_REFRESH_SECRET=your_refresh_secret_key_here
JWT_EXPIRES_IN=15m
JWT_REFRESH_EXPIRES_IN=7d

# Bcrypt
BCRYPT_ROUNDS=12

# Email (SMTP)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your_email@gmail.com
SMTP_PASSWORD=your_email_password
EMAIL_FROM=noreply@yourstore.com

# AWS S3
AWS_ACCESS_KEY_ID=your_aws_access_key
AWS_SECRET_ACCESS_KEY=your_aws_secret_key
AWS_REGION=us-east-1
AWS_S3_BUCKET=your-bucket-name

# Stripe
STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key
STRIPE_PUBLISHABLE_KEY=pk_test_your_stripe_publishable_key
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret

# CORS
CORS_ORIGIN=http://localhost:3001,https://yourfrontend.com

# Rate Limiting
RATE_LIMIT_WINDOW=15m
RATE_LIMIT_MAX_REQUESTS=100

# Logging
LOG_LEVEL=info
LOG_FILE_PATH=./logs

Database Configuration

Edit src/config/database.js if needed:

module.exports = {
  development: {
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    dialect: 'postgres',
    pool: {
      max: parseInt(process.env.DB_POOL_MAX),
      min: parseInt(process.env.DB_POOL_MIN),
      acquire: 30000,
      idle: 10000
    }
  }
};

🏃 Running the Application

Development Mode

# Start with nodemon (auto-reload)
npm run dev

Production Mode

# Build and start
npm start

Using Docker

# Build and run all services
docker-compose up -d

# View logs
docker-compose logs -f api

# Stop services
docker-compose down

Available Scripts

npm start          # Start production server
npm run dev        # Start development server with nodemon
npm test           # Run tests
npm run test:watch # Run tests in watch mode
npm run test:coverage # Generate test coverage report
npm run migrate    # Run database migrations
npm run migrate:undo # Undo last migration
npm run seed       # Seed database with sample data
npm run lint       # Run ESLint
npm run lint:fix   # Fix ESLint errors
npm run docs       # Generate API documentation

📚 API Documentation

Base URL

Development: http://localhost:3000/api/v1
Production: https://api.yourstore.com/api/v1

Authentication

Most endpoints require a JWT token in the Authorization header:

Authorization: Bearer <your_jwt_token>

Core Endpoints

Authentication

POST /api/v1/auth/register
POST /api/v1/auth/login
POST /api/v1/auth/logout
POST /api/v1/auth/refresh-token
POST /api/v1/auth/verify-email
POST /api/v1/auth/forgot-password
POST /api/v1/auth/reset-password

Example: User Registration

curl -X POST http://localhost:3000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "SecurePass123!",
    "firstName": "John",
    "lastName": "Doe"
  }'

Response:

{
  "success": true,
  "message": "Registration successful. Please verify your email.",
  "data": {
    "userId": "uuid-here",
    "email": "user@example.com"
  }
}

Example: User Login

curl -X POST http://localhost:3000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "SecurePass123!"
  }'

Response:

{
  "success": true,
  "data": {
    "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "user": {
      "id": "uuid-here",
      "email": "user@example.com",
      "firstName": "John",
      "lastName": "Doe",
      "role": "user"
    }
  }
}

Products

GET    /api/v1/products              # List all products (paginated)
GET    /api/v1/products/:id          # Get single product
POST   /api/v1/products              # Create product (Admin)
PUT    /api/v1/products/:id          # Update product (Admin)
DELETE /api/v1/products/:id          # Delete product (Admin)
GET    /api/v1/products/search       # Search products
POST   /api/v1/products/:id/images   # Upload product image (Admin)

Example: Get Products

curl -X GET "http://localhost:3000/api/v1/products?page=1&limit=10&category=electronics&sort=price:asc"

Response:

{
  "success": true,
  "data": {
    "products": [
      {
        "id": "uuid-here",
        "name": "Premium Headphones",
        "description": "High-quality wireless headphones",
        "price": 199.99,
        "sku": "HD-001",
        "stock": 50,
        "category": "electronics",
        "images": ["https://s3.amazonaws.com/..."],
        "createdAt": "2024-01-15T10:00:00Z"
      }
    ],
    "pagination": {
      "page": 1,
      "limit": 10,
      "total": 150,
      "pages": 15
    }
  }
}

Example: Create Product

curl -X POST http://localhost:3000/api/v1/products \
  -H "Authorization: Bearer <admin_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Wireless Mouse",
    "description": "Ergonomic wireless mouse",
    "price": 29.99,
    "sku": "MS-001",
    "stock": 100,
    "categoryId": "category-uuid"
  }'

Categories

GET    /api/v1/categories            # List all categories
GET    /api/v1/categories/:id        # Get single category
POST   /api/v1/categories            # Create category (Admin)
PUT    /api/v1/categories/:id        # Update category (Admin)
DELETE /api/v1/categories/:id        # Delete category (Admin)

Shopping Cart

GET    /api/v1/cart                  # Get user's cart
POST   /api/v1/cart/items            # Add item to cart
PUT    /api/v1/cart/items/:id        # Update cart item quantity
DELETE /api/v1/cart/items/:id        # Remove item from cart
DELETE /api/v1/cart                  # Clear cart

Example: Add to Cart

curl -X POST http://localhost:3000/api/v1/cart/items \
  -H "Authorization: Bearer <user_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "productId": "product-uuid",
    "quantity": 2
  }'

Response:

{
  "success": true,
  "data": {
    "cart": {
      "id": "cart-uuid",
      "items": [
        {
          "id": "item-uuid",
          "productId": "product-uuid",
          "name": "Wireless Mouse",
          "price": 29.99,
          "quantity": 2,
          "subtotal": 59.98
        }
      ],
      "total": 59.98
    }
  }
}

Orders

GET    /api/v1/orders                # Get user's orders
GET    /api/v1/orders/:id            # Get single order
POST   /api/v1/orders                # Create order from cart
PUT    /api/v1/orders/:id/cancel     # Cancel order
GET    /api/v1/orders/:id/invoice    # Download invoice

Example: Create Order

curl -X POST http://localhost:3000/api/v1/orders \
  -H "Authorization: Bearer <user_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "shippingAddress": {
      "street": "123 Main St",
      "city": "New York",
      "state": "NY",
      "zipCode": "10001",
      "country": "USA"
    },
    "paymentMethodId": "pm_card_visa"
  }'

Response:

{
  "success": true,
  "data": {
    "order": {
      "id": "order-uuid",
      "orderNumber": "ORD-20240115-001",
      "status": "pending",
      "items": [...],
      "subtotal": 59.98,
      "tax": 4.80,
      "shipping": 10.00,
      "total": 74.78,
      "createdAt": "2024-01-15T10:00:00Z"
    },
    "paymentIntent": {
      "id": "pi_stripe_id",
      "clientSecret": "pi_secret_here"
    }
  }
}

Admin Endpoints

GET    /api/v1/admin/users           # List all users
PUT    /api/v1/admin/users/:id/role  # Update user role
GET    /api/v1/admin/orders          # List all orders
PUT    /api/v1/admin/orders/:id      # Update order status
GET    /api/v1/admin/analytics       # Get sales analytics
POST   /api/v1/admin/products/import # Bulk import products
GET    /api/v1/admin/products/export # Bulk export products

Swagger Documentation

Access interactive API documentation at:

http://localhost:3000/api-docs

🧪 Testing

Running Tests

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Generate coverage report
npm run test:coverage

# Run specific test file
npm test -- src/tests/auth.test.js

Test Structure

// Example test file: src/tests/auth.test.js
describe('Authentication API', () => {
  describe('POST /api/v1/auth/register', () => {
    it('should register a new user', async () => {
      const response = await request(app)
        .post('/api/v1/auth/register')
        .send({
          email: 'test@example.com',
          password: 'SecurePass123!',
          firstName: 

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors