Skip to content

hamdytoto/Africa_Store_Backend

Repository files navigation

Africa Store Backend

A Production-Ready E-Commerce Backend API

A sophisticated, fully-featured e-commerce backend built with NestJS, MongoDB, and TypeScript. Africa Store Backend provides a complete REST API with real-time capabilities, secure authentication, payment processing, and advanced business logic for modern e-commerce applications.

Node TypeScript NestJS MongoDB License


📋 Table of Contents


Overview

Africa Store Backend is a comprehensive e-commerce API solution designed with scalability, security, and developer experience in mind. It supports multi-user management, complex product catalogs, shopping cart operations, order processing with payment integration, promotional campaigns via coupons, and real-time inventory updates.

Built for production-grade applications requiring robust authentication, secure payment handling, and real-time communication channels.


Tech Stack

Layer Technology
Runtime Node.js 18+
Framework NestJS 11.0+
Language TypeScript 5.7+
Database MongoDB 4.0+ (via Mongoose ODM)
API GraphQL Apollo Server 5.4
Authentication JWT + OTP
Caching Redis + In-Memory Cache Manager
File Storage Cloudinary
Real-time Socket.IO
Payments Stripe
Email Resend & Brevo (Brevo/Sendinblue)
Validation class-validator, class-transformer
Testing Jest, Supertest
Security bcrypt, dotenv, CORS

Key Features

🔐 Authentication & Authorization

  • OTP-Based Registration: Secure registration flow with one-time passwords sent via email
  • JWT Authentication: Dual-token system with access tokens and refresh tokens
    • Access Token: Short-lived (configurable, default 1h)
    • Refresh Token: Long-lived (configurable, default 7 days)
  • Role-Based Access Control (RBAC): User and Admin roles with permission-based guards
  • Password Security: bcrypt hashing with salt rounds for secure password storage
  • Token Management: Token whitelist/blacklist for logout functionality

👥 User Management

  • Complete user profile management
  • Flexible authentication flows (registration, login, refresh tokens)
  • Password reset functionality with secure OTP verification
  • User metadata and preference storage
  • Role-based user distinction (standard users vs administrators)

📦 Product & Inventory Management

  • Product Catalog: Full CRUD operations for products
    • Product details: name, description, price, SKU
    • Multi-image support with Cloudinary integration
    • Stock level tracking with real-time updates
    • Product status management (active/inactive)
    • Search, filter, and sorting capabilities

🏷️ Category Management

  • Hierarchical category organization
  • Category-to-product relationships
  • Bulk category operations
  • Category-based product filtering

🛒 Shopping Cart System

  • Session-based or user-specific shopping carts
  • Add, update, and remove cart items
  • Real-time cart total calculations (subtotal, tax, discounts)
  • Cart persistence across sessions
  • Automatic calculation of pricing with applied coupons

💳 Order Processing & Management

  • Complete order lifecycle management
  • Multiple order statuses (pending, processing, shipped, delivered, cancelled)
  • Order history tracking with detailed order information
  • Relationship mapping to users, products, and cart items
  • Order summary with pricing breakdown

💰 Payment Integration (Stripe)

  • Stripe Checkout Sessions: Create checkout sessions for secure payment processing
  • Webhook Handling: Secure webhook processing for payment confirmations
    • Automatic order confirmation on successful payment
    • Invoice generation and delivery
    • Handle various Stripe events (payment succeeded, failed, etc.)
  • Payment Reconciliation: Automatic synchronization of payment status with orders
  • Webhook Verification: HMAC-SHA256 signature verification for secure webhooks

🎟️ Coupon & Discount System

  • Create and manage discount coupons
  • Coupon validation and application
  • Discount percentage or fixed amount support
  • Usage limit tracking per coupon
  • Expiration date management
  • Automatic discount calculation on cart/orders

📧 Email Notifications

  • Multi-Provider Support:
    • Resend: Modern email delivery service
    • Brevo (Sendinblue): Traditional email marketing platform
  • Email Templates: Handlebars-based templating for dynamic email generation
  • Automated Emails:
    • OTP verification emails
    • Order confirmation emails
    • Payment receipt emails
    • Password reset instructions
    • User welcome emails

📁 File Upload & Management

  • Cloudinary Integration: Cloud-based image storage
  • Upload Types:
    • Product images and thumbnails
    • User profile pictures
    • Dynamic file resizing and optimization
  • URL Generation: Auto-generated CDN URLs for optimized delivery
  • Folder Organization: Organized cloud folder structure for easy management

🔄 Real-time Features (WebSockets)

  • Socket.IO Integration: Bi-directional communication channel
  • Real-time Inventory Updates: Instant stock level synchronization
  • Live Notifications: User notifications for order status changes
  • Broadcast Events: System-wide announcements
  • Connection Management: Automatic reconnection and fallback handling

🏠 Homepage & Featured Content

  • Homepage configuration and management
  • Featured products showcase
  • Promotional banner management
  • Dynamic content updates

📊 Caching & Performance

  • Multi-Level Caching:
    • Redis-backed distributed cache
    • In-memory cache for immediate lookups
  • Cache Invalidation: Automatic cache update on data changes
  • Performance Optimization: Reduced database queries

🧪 Testing & Quality Assurance

  • Unit Tests: Jest-based unit test suite with high coverage
  • End-to-End Tests: Supertest integration tests
  • Mocking: Complete mock support for external dependencies
  • Coverage Reports: Code coverage analysis

🌍 Data Seeding

  • Faker-Based Data Generation: Realistic test data generation
  • Seed Scripts:
    • User seed script (admin + regular users)
    • Product seed script (with categories)
    • Category seed script
  • Development Convenience: Quick database population for development

🛡️ Security Features

  • CORS Configuration: Cross-origin resource sharing setup
  • HTTP Exception Handling: Centralized exception filtering
  • Response Standardization: Consistent API response format
  • Input Validation: Class-validator based DTO validation
  • Error Handling: Global error handling with descriptive messages
  • Middleware: Request logging and authentication middleware
  • Non-Whitelisted Field Rejection: Strict request payload validation

📡 API Documentation

  • RESTful API design with clear endpoint structure
  • GraphQL support via Apollo Server
  • Request/Response standardization
  • Comprehensive error messages

Architecture

The application follows a modular, layered architecture:

┌─────────────────────────────────────┐
│      REST API / GraphQL Layer       │
├─────────────────────────────────────┤
│        Controllers & Routes         │
├─────────────────────────────────────┤
│  Services & Business Logic          │
├─────────────────────────────────────┤
│  Data Access Layer (Repositories)   │
├─────────────────────────────────────┤
│   MongoDB / Mongoose Models         │
├─────────────────────────────────────┤
│  External Services: Stripe, Resend  │
│  Cloudinary, Socket.IO              │
└─────────────────────────────────────┘

Design Patterns Used:

  • Repository Pattern: Abstracted database access
  • Dependency Injection: NestJS built-in DI system
  • Module Pattern: Feature-based module organization
  • Guard & Interceptor Pattern: Cross-cutting concerns (auth, logging, error handling)
  • DTO Pattern: Type-safe request/response validation

Quick Start

Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js 18.0.0 or higher
  • npm 8.0.0 or higher (or yarn/pnpm)
  • MongoDB instance (Atlas, Docker, or self-hosted)
  • Git for version control

Installation

  1. Clone the repository

    git clone <repository-url> africa-store-backend
    cd africa-store-backend
  2. Install dependencies

    npm install
  3. Create environment configuration

    cp .env.example .env
    # Edit .env with your configuration (see Environment Setup below)
  4. Start the development server

    npm run start:dev

    The API will be available at: http://localhost:3000

  5. (Optional) Seed the database with sample data

    npm run seed

Verify Installation

Check if the server is running:

curl http://localhost:3000/health

Expected response:

{
  "status": "ok",
  "timestamp": "2026-02-13T10:30:00Z"
}

Environment Setup

Configuration File (.env)

Create a .env file in the root directory with the following variables:

# ============================================
# Application Configuration
# ============================================
NODE_ENV=development
PORT=3000
API_BASE_URL=http://localhost:3000

# ============================================
# Database Configuration
# ============================================
MONGODB_URI=mongodb+srv://username:[email protected]/africa_store?retryWrites=true&w=majority

# ============================================
# JWT Authentication
# ============================================
TOKEN_SECRET=your_super_secret_jwt_key_change_this_in_production
TOKEN_EXPIRES_IN=1h
REFRESH_TOKEN_SECRET=your_super_secret_refresh_token_key
REFRESH_TOKEN_EXPIRES_IN=7d

# ============================================
# Cloudinary (File Upload)
# ============================================
CLOUD_NAME=your_cloudinary_cloud_name
CLOUD_API_KEY=your_cloudinary_api_key
CLOUD_API_SECRET=your_cloudinary_api_secret
CLOUD_ROOT_FOLDER=africa-store

# ============================================
# Email Configuration - Resend
# ============================================
RESEND_API_KEY=re_your_resend_api_key
RESEND_FROM=[email protected]

# ============================================
# Email Configuration - Brevo (Sendinblue)
# ============================================
BREVO_API_KEY=your_brevo_api_key
MAIL_FROM=[email protected]

# ============================================
# Stripe Payment Processing
# ============================================
STRIPE_SECRET_KEY=sk_test_your_test_secret_key
STRIPE_PUBLIC_KEY=pk_test_your_test_public_key
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret

# ============================================
# Redis Cache (Optional)
# ============================================
REDIS_URL=redis://localhost:6379/0
REDIS_TTL=3600

# ============================================
# OTP Configuration
# ============================================
OTP_EXPIRY_TIME=10m
OTP_LENGTH=6

Environment Variable Explanations

Variable Purpose Example
NODE_ENV Application environment development, production
PORT Server port 3000
MONGODB_URI MongoDB connection string MongoDB Atlas or local instance
TOKEN_SECRET JWT signing secret (access token) Use a strong random string
TOKEN_EXPIRES_IN Access token expiration 1h, 24h
CLOUD_NAME Cloudinary account name Find in Cloudinary dashboard
CLOUD_API_KEY/SECRET Cloudinary credentials Cloudinary dashboard
RESEND_API_KEY Resend email service key Resend dashboard
STRIPE_SECRET_KEY Stripe secret key Stripe test/live keys
STRIPE_WEBHOOK_SECRET Stripe webhook signing secret From Stripe webhook settings

Getting API Keys

MongoDB Atlas:

  1. Visit https://www.mongodb.com/cloud/atlas
  2. Create a free cluster
  3. Get connection string from "Connect" button

Cloudinary:

  1. Visit https://cloudinary.com (free tier available)
  2. Sign up and navigate to dashboard
  3. Copy Cloud Name, API Key, and API Secret

Stripe:

  1. Visit https://stripe.com
  2. Create account and navigate to API Keys
  3. Use test keys for development

Resend:

  1. Visit https://resend.com (free tier available)
  2. Create account and generate API key
  3. Verify sender email domain

Project Structure

africa-store-backend/
│
├── src/
│   ├── main.ts                          # Application entry point
│   ├── app.module.ts                    # Root module
│   ├── app.controller.ts                # Root controller
│   ├── app.service.ts                   # Root service
│   │
│   ├── common/                          # Shared utilities & cross-cutting concerns
│   │   ├── constants/
│   │   │   └── constants.ts             # Application constants
│   │   ├── decorators/                  # Custom decorators
│   │   │   ├── auth/                    # Auth-related decorators
│   │   │   └── validation/              # Validation decorators
│   │   ├── exceptions/
│   │   │   └── validation.exception.ts  # Custom validation exceptions
│   │   ├── filters/                     # Exception filters
│   │   │   ├── all-exceptions.filter.ts # Global exception handler
│   │   │   └── httpexception.filter.ts  # HTTP exception handler
│   │   ├── guards/                      # Authentication & Authorization
│   │   │   ├── authentication.guard.ts  # JWT verification guard
│   │   │   └── authorization.guard.ts   # Role-based access control
│   │   ├── interceptors/                # Request/response processing
│   │   │   ├── error-handler.interceptor.ts   # Error handling
│   │   │   └── success-response.interceptor.ts # Response standardization
│   │   ├── middlewares/
│   │   │   └── logger.middleware.ts     # Request logging middleware
│   │   ├── pipes/
│   │   │   └── objectid-validation.pipe.ts # MongoDB ObjectId validation
│   │   ├── security/
│   │   │   └── hash.util.ts             # Password hashing utilities
│   │   ├── services/                    # External service integrations
│   │   │   ├── fileupload/              # Cloudinary integration
│   │   │   └── payment/                 # Stripe integration
│   │   ├── types/
│   │   │   └── image.type.ts            # Type definitions
│   │   └── utils/
│   │       └── validation.mapper.ts     # Validation error mapping
│   │
│   ├── db/                              # Database layer
│   │   ├── enums/                       # Enumeration types
│   │   │   ├── token.enum.ts            # Token-related enums
│   │   │   └── user.enum.ts             # User-related enums
│   │   ├── models/                      # Mongoose schemas & models
│   │   │   ├── user.model.ts            # User schema
│   │   │   ├── product.model.ts         # Product schema
│   │   │   ├── category.model.ts        # Category schema
│   │   │   ├── cart.model.ts            # Shopping cart schema
│   │   │   ├── order.model.ts           # Order schema
│   │   │   ├── coupon.model.ts          # Coupon/discount schema
│   │   │   ├── token.model.ts           # Token blacklist schema
│   │   │   ├── otp.model.ts             # OTP storage schema
│   │   │   └── home.model.ts            # Homepage content schema
│   │   └── repos/                       # Repository layer (data access)
│   │       ├── abstract.repository.ts   # Base repository class
│   │       ├── user.repository.ts       # User repository
│   │       ├── product.repository.ts    # Product repository
│   │       ├── category.repository.ts   # Category repository
│   │       ├── cart.repository.ts       # Cart repository
│   │       ├── order.repository.ts      # Order repository
│   │       ├── coupon.repository.ts     # Coupon repository
│   │       ├── token.repository.ts      # Token repository
│   │       ├── otp.repository.ts        # OTP repository
│   │       └── home.repository.ts       # Homepage repository
│   │
│   ├── modules/                         # Feature modules
│   │   ├── auth/                        # Authentication module
│   │   │   ├── auth.service.ts          # Auth business logic
│   │   │   ├── auth.controller.ts       # Auth endpoints
│   │   │   ├── auth.module.ts           # Auth module definition
│   │   │   └── dto/                     # Auth DTOs (login, register, etc.)
│   │   │
│   │   ├── user/                        # User management module
│   │   │   ├── user.service.ts          # User business logic
│   │   │   ├── user.controller.ts       # User endpoints
│   │   │   ├── user.module.ts           # User module definition
│   │   │   └── dto/                     # User DTOs
│   │   │
│   │   ├── product/                     # Product catalog module
│   │   │   ├── product.service.ts       # Product business logic
│   │   │   ├── product.controller.ts    # Product endpoints
│   │   │   ├── product.module.ts        # Product module definition
│   │   │   └── dto/                     # Product DTOs
│   │   │
│   │   ├── category/                    # Category management module
│   │   │   ├── category.service.ts      # Category business logic
│   │   │   ├── category.controller.ts   # Category endpoints
│   │   │   ├── category.module.ts       # Category module definition
│   │   │   └── dto/                     # Category DTOs
│   │   │
│   │   ├── cart/                        # Shopping cart module
│   │   │   ├── cart.service.ts          # Cart business logic
│   │   │   ├── cart.controller.ts       # Cart endpoints
│   │   │   ├── cart.module.ts           # Cart module definition
│   │   │   └── dto/                     # Cart DTOs
│   │   │
│   │   ├── order/                       # Order processing module
│   │   │   ├── order.service.ts         # Order business logic
│   │   │   ├── order.controller.ts      # Order endpoints
│   │   │   ├── order.module.ts          # Order module definition
│   │   │   └── dto/                     # Order DTOs
│   │   │
│   │   ├── coupon/                      # Coupon & discount module
│   │   │   ├── coupon.service.ts        # Coupon business logic
│   │   │   ├── coupon.controller.ts     # Coupon endpoints
│   │   │   ├── coupon.module.ts         # Coupon module definition
│   │   │   └── dto/                     # Coupon DTOs
│   │   │
│   │   ├── mail/                        # Email sending module
│   │   │   ├── mail.service.ts          # Mail business logic
│   │   │   ├── mail.controller.ts       # Mail endpoints
│   │   │   └── mail.module.ts           # Mail module definition
│   │   │
│   │   ├── mailer/                      # Email provider configuration
│   │   │   ├── mailer.module.ts         # Base mailer setup
│   │   │   ├── resend-mail.module.ts    # Resend provider config
│   │   │   └── ...                      # Other email providers
│   │   │
│   │   ├── home/                        # Homepage content module
│   │   │   ├── home.service.ts          # Home business logic
│   │   │   ├── home.controller.ts       # Home endpoints
│   │   │   ├── home.module.ts           # Home module definition
│   │   │   └── dto/                     # Home DTOs
│   │   │
│   │   ├── socket/                      # WebSocket/Socket.IO module
│   │   │   └── ...                      # Real-time features
│   │   │
│   │   └── test/                        # Testing module
│   │       └── schema.gql               # GraphQL schema
│   │
│   ├── seeds/                           # Data seeding scripts
│   │   ├── seed.ts                      # Main seed script entry
│   │   ├── seed-users.ts                # User data seeding
│   │   ├── seed-categories.ts           # Category data seeding
│   │   ├── seed-products.ts             # Product data seeding
│   │   └── generators/                  # Faker-based data generators
│   │
│   └── templates/                       # Email templates
│       └── otp.hbs                      # Handlebars email templates
│
├── test/                                # End-to-end tests
│   ├── app.e2e-spec.ts                  # E2E test suite
│   └── jest-e2e.json                    # Jest E2E configuration
│
├── dist/                                # Compiled output (generated)
├── node_modules/                        # Dependencies
│
├── .env.example                         # Environment variables template
├── .gitignore                           # Git ignore rules
├── Dockerfile                           # Docker containerization
├── docker-compose.yml                   # Docker compose (if available)
├── eslint.config.mjs                    # ESLint configuration
├── nest-cli.json                        # NestJS CLI configuration
├── package.json                         # Dependencies & scripts
├── package-lock.json                    # Dependency lock file
├── tsconfig.json                        # TypeScript configuration
├── tsconfig.build.json                  # TypeScript build configuration
└── README.md                            # This file

API Modules

🔐 Auth Module (/auth)

Handles user authentication and token management.

Endpoints:

  • POST /auth/register - Register new user with OTP
  • POST /auth/verify-otp - Verify OTP and create account
  • POST /auth/login - Login and get JWT tokens
  • POST /auth/refresh - Refresh access token
  • POST /auth/logout - Logout and invalidate tokens
  • POST /auth/forgot-password - Initiate password reset
  • POST /auth/reset-password - Reset password with OTP

Key Features:

  • OTP-based secure registration
  • Dual JWT token system
  • Automatic token refresh mechanism
  • Secure password handling

👥 User Module (/users)

Manages user profiles and account settings.

Endpoints:

  • GET /users/:id - Get user details
  • PUT /users/:id - Update user profile
  • GET /users - List all users (admin only)
  • DELETE /users/:id - Delete user account

Key Features:

  • User profile management
  • Role tracking (admin/user)
  • User metadata storage

📦 Product Module (/products)

Manages product catalog and inventory.

Endpoints:

  • GET /products - List products with filters, search, pagination
  • GET /products/:id - Get product details
  • POST /products - Create new product (admin)
  • PUT /products/:id - Update product (admin)
  • DELETE /products/:id - Delete product (admin)
  • GET /products/search - Search products by name/description
  • PUT /products/:id/stock - Update product stock levels

Key Features:

  • Full-text search capabilities
  • Stock level tracking
  • Price and discount management
  • Image management via Cloudinary
  • Product status (active/inactive)
  • Filtering by category, price range, etc.

🏷️ Category Module (/categories)

Manages product categories.

Endpoints:

  • GET /categories - List all categories
  • GET /categories/:id - Get category details
  • POST /categories - Create category (admin)
  • PUT /categories/:id - Update category (admin)
  • DELETE /categories/:id - Delete category (admin)
  • GET /categories/:id/products - Get products in category

Key Features:

  • Hierarchical category support
  • Product association
  • Category-based filtering

🛒 Cart Module (/carts)

Manages shopping carts and cart items.

Endpoints:

  • GET /carts/:id - Get cart contents
  • POST /carts/:id/items - Add item to cart
  • PUT /carts/:id/items/:itemId - Update item quantity
  • DELETE /carts/:id/items/:itemId - Remove item from cart
  • DELETE /carts/:id - Clear cart
  • GET /carts/:id/total - Get cart total with taxes/discounts

Key Features:

  • Real-time price calculations
  • Coupon application
  • Tax calculation
  • Cart persistence

💳 Order Module (/orders)

Manages order processing and fulfillment.

Endpoints:

  • GET /orders - List user orders
  • GET /orders/:id - Get order details
  • POST /orders - Create new order
  • PUT /orders/:id/status - Update order status (admin)
  • POST /orders/webhook/stripe - Stripe payment webhook
  • GET /orders/:id/invoice - Download order invoice

Key Features:

  • Order lifecycle management
  • Status tracking (pending, processing, shipped, delivered)
  • Payment status integration
  • Invoice generation

💰 Coupon Module (/coupons)

Manages discount coupon system.

Endpoints:

  • GET /coupons - List active coupons
  • POST /coupons - Create coupon (admin)
  • PUT /coupons/:id - Update coupon (admin)
  • DELETE /coupons/:id - Delete coupon (admin)
  • POST /coupons/:code/validate - Validate coupon code

Key Features:

  • Percentage and fixed-amount discounts
  • Usage limits and expiration dates
  • Code-based validation
  • Usage tracking

📧 Mail Module (/mail)

Handles email notifications.

Endpoints:

  • POST /mail/send - Send email (admin)
  • POST /mail/send-bulk - Send bulk emails (admin)

Automatic Emails Sent:

  • OTP registration emails
  • Order confirmation emails
  • Payment receipt emails
  • Password reset emails
  • Shipment tracking updates

🏠 Home Module (/home)

Manages homepage content and featured items.

Endpoints:

  • GET /home - Get homepage configuration
  • PUT /home - Update homepage (admin)
  • GET /home/featured-products - Get featured products
  • POST /home/featured-products - Add featured product (admin)

Database Models

All models are defined using Mongoose with TypeScript support.

User Model

{
  email: string (unique)
  firstName: string
  lastName: string
  passwordHash: string (bcrypt hashed)
  role: 'user' | 'admin'
  isEmailVerified: boolean
  profilePicture?: string (Cloudinary URL)
  phoneNumber?: string
  address?: object
  createdAt: Date
  updatedAt: Date
  lastLogin?: Date
}

Product Model

{
  name: string
  description: string
  slug: string (URL-friendly)
  sku: string (unique)
  price: number
  comparePrice?: number (original price)
  discount?: number (percentage)
  images: string[] (Cloudinary URLs)
  thumbnail: string
  category: ObjectId (reference to Category)
  stock: number
  isActive: boolean
  rating?: number
  reviews?: object[]
  metadata?: object (custom fields)
  createdAt: Date
  updatedAt: Date
}

Category Model

{
  name: string
  slug: string (unique)
  description?: string
  image?: string (Cloudinary URL)
  isActive: boolean
  parentCategory?: ObjectId (for hierarchical structure)
  createdAt: Date
  updatedAt: Date
}

Order Model

{
  orderNumber: string (unique)
  user: ObjectId (reference to User)
  items: object[] (product references with quantities)
  subtotal: number
  tax: number
  discountAmount: number
  appliedCoupon?: ObjectId (reference to Coupon)
  total: number
  status: 'pending' | 'processing' | 'shipped' | 'delivered' | 'cancelled'
  paymentStatus: 'pending' | 'succeeded' | 'failed'
  paymentMethod: 'stripe' | 'cash'
  stripeSessionId?: string
  shippingAddress: object
  trackingNumber?: string
  notes?: string
  createdAt: Date
  updatedAt: Date
}

Cart Model

{
  user: ObjectId (reference to User)
  items: object[] (product references with quantities)
  subtotal: number
  tax: number
  discount: number
  appliedCoupon?: ObjectId (reference to Coupon)
  total: number
  expiresAt: Date
  createdAt: Date
  updatedAt: Date
}

Coupon Model

{
  code: string (unique, uppercase)
  description?: string
  discountType: 'percentage' | 'fixed'
  discountValue: number
  minPurchaseAmount?: number
  maxUsageCount?: number
  currentUsageCount: number
  usedBy: ObjectId[] (references to Users)
  expiryDate: Date
  isActive: boolean
  createdAt: Date
  updatedAt: Date
}

Authentication & Security

JWT Token Flow

1. User registers/logs in
2. Server generates:
   - Access Token (short-lived, 1h default)
   - Refresh Token (long-lived, 7d default)
3. Client stores tokens
4. For protected routes:
   - Client sends access token in Authorization header
   - Server validates token signature & expiration
5. When access token expires:
   - Client uses refresh token to get new access token
   - Server validates refresh token in database

OTP Flow

1. User initiates action (register, reset password)
2. Server generates 6-digit OTP
3. Email sent via Resend/Brevo
4. User enters OTP in app
5. Server validates OTP (must match & not expired)
6. Upon successful validation, action is completed

Security Headers & Middleware

  • CORS: Enabled for cross-origin requests
  • HTTPS: Recommended for production
  • Password Hashing: bcrypt with 10 salt rounds
  • Rate Limiting: Recommended via API gateway
  • Input Validation: Class-validator on all DTOs
  • SQL/NoSQL Injection Prevention: Mongoose schema validation

File Management

All file uploads are handled through Cloudinary cloud storage.

Upload Process

  1. Client uploads file
  2. Server validates file type & size
  3. File sent to Cloudinary
  4. Cloudinary returns secure URL
  5. URL stored in MongoDB
  6. CDN URL returned to client

Supported File Types

  • Images: JPG, PNG, GIF, WebP
  • Max Size: 10MB (configurable)

Folder Structure in Cloudinary

africa-store/
├── products/
│   ├── images/
│   └── thumbnails/
├── users/
│   └── profiles/
└── documents/
    └── invoices/

Payment Processing

Stripe Integration

Checkout Flow:

  1. User clicks "Proceed to Payment"
  2. Server creates Stripe Checkout Session
  3. Server returns session ID to client
  4. Client redirects to Stripe Checkout
  5. User enters payment details
  6. Stripe processes transaction

Webhook Handling:

  1. Stripe sends webhook event to /order/webhook
  2. Server verifies webhook signature
  3. Order status updated based on payment result
  4. Invoice and confirmation email sent
  5. Inventory updated

Supported Payment Methods:

  • Credit/Debit Cards (Visa, Mastercard, Amex)
  • Digital Wallets (Apple Pay, Google Pay)
  • Bank Transfers (region-specific)

Email Notifications

Email Providers

Resend (Recommended)

  • Modern email delivery
  • Great deliverability rates
  • Free tier available
  • Real-time email logs

Brevo (Sendinblue)

  • Traditional email marketing
  • Higher volume support
  • SMTP integration available
  • Free tier with limited sends

Email Templates

All emails use Handlebars templating engine for dynamic content.

Available Templates:

  • otp.hbs - OTP verification emails
  • order-confirmation.hbs - Order confirmations
  • payment-receipt.hbs - Payment receipts
  • password-reset.hbs - Password reset links
  • welcome.hbs - Welcome emails

Real-time Features

Socket.IO Events

Client → Server:

// Real-time notifications
socket.on('order:trackingUpdate', (data) => {})

// Live product updates
socket.on('product:viewed', (productId) => {})

Server → Client:

// Broadcast product stock update
io.emit('product:stocked', { productId, newStock })

// Order status update
socket.emit('order:statusChanged', { orderId, status })

// System announcements
io.emit('announcement:broadcast', { message })

Testing

Running Tests

# Unit tests
npm run test

# Unit tests with coverage
npm run test:cov

# E2E tests
npm run test:e2e

# Tests in watch mode
npm run test:watch

# Debug tests
npm run test:debug

Test Files

  • Unit Tests: *.spec.ts files alongside source code
  • E2E Tests: Located in /test directory
  • Configuration: jest.config.js and jest-e2e.json

Coverage Reports

Generate coverage report:

npm run test:cov

Report location: coverage/ directory


Docker Deployment

Build Docker Image

docker build -t africa-store-backend:latest .

Run Container

docker run \
  -e MONGODB_URI="your_mongodb_uri" \
  -e STRIPE_SECRET_KEY="your_stripe_key" \
  -e PORT=3000 \
  -p 3000:3000 \
  africa-store-backend:latest

Docker Compose (if available)

docker-compose up -d

View Logs

docker logs -f container_id

Development

Scripts

# Development
npm run start          # Start server (production)
npm run start:dev     # Start with hot reload
npm run start:debug   # Start with debugger

# Building
npm run build         # Compile TypeScript to JavaScript

# Code Quality
npm run lint          # Run ESLint
npm run format        # Format code with Prettier

# Database
npm run seed          # Seed database with sample data
npm run mongo:cli     # Connect to MongoDB CLI

# Testing
npm run test          # Run unit tests
npm run test:e2e      # Run E2E tests
npm run test:cov      # Generate coverage report

Code Style

  • ESLint: Enforces code standards
  • Prettier: Code formatting
  • TypeScript: Type safety
# Fix all linting issues
npm run lint

# Format all files
npm run format

Hot Module Reloading

Development mode includes automatic restart on file changes:

npm run start:dev

Troubleshooting

Common Issues

Issue 1: MongoDB Connection Error

Error: connect ECONNREFUSED

Solution:

  • Verify MONGODB_URI in .env
  • Ensure MongoDB instance is running
  • Check network/firewall settings

Issue 2: Stripe Webhook Not Working

Error: Invalid signature from Stripe

Solution:

  • Verify STRIPE_WEBHOOK_SECRET matches Stripe dashboard
  • Ensure webhook endpoint is publicly accessible
  • Check webhook signing in Stripe settings

Issue 3: Cloudinary Upload Fails

Error: Cloudinary authentication failed

Solution:

  • Verify CLOUD_NAME, CLOUD_API_KEY, CLOUD_API_SECRET
  • Check Cloudinary account is active
  • Verify API key permissions

Issue 4: Email Not Sending

Error: Email service unavailable

Solution:

  • Verify RESEND_API_KEY or BREVO_API_KEY
  • Check sender email is verified
  • Verify email template exists
  • Check spam folder

Issue 5: Port Already in Use

Error: EADDRINUSE: address already in use :::3000

Solution:

# Find process using port
netstat -ano | findstr :3000  # Windows
lsof -i :3000                  # Mac/Linux

# Kill process (Windows)
taskkill /PID <PID> /F

# Change PORT in .env
PORT=3001

Debug Mode

Start server with debugging enabled:

npm run start:debug

Open Chrome DevTools or VS Code debugger:

  • VS Code: Press F5 or go to Debug menu

Logging

Check application logs:

# If deployed on cloud
docker logs -f container_id

# Local development
# Check terminal output

Contributing

Contribution Guidelines

  1. Fork the repository
  2. Create a feature branch
    git checkout -b feature/awesome-feature
  3. Make your changes
  4. Test your changes
    npm run test
    npm run lint
  5. Commit with clear messages
    git commit -m "feat: add awesome feature"
  6. Push to your fork
    git push origin feature/awesome-feature
  7. Create a Pull Request

Best Practices

  • Follow existing code style
  • Write meaningful commit messages
  • Add tests for new features
  • Update documentation
  • Keep PRs focused and small
  • Never commit .env or secrets

Reporting Issues

When reporting issues, please include:

  • Clear description of the problem
  • Steps to reproduce
  • Expected vs. actual behavior
  • Environment details (OS, Node version, etc.)
  • Relevant error messages or logs

License

© 2026 Africa Store. All rights reserved.

This repository is currently marked as UNLICENSED in package.json. Please review and update the license when publishing this project.

Recommended Licenses:

  • MIT: Permissive, widely used
  • Apache 2.0: Patent protection included
  • UNLICENSED: Proprietary (current)

Support & Contact

For support:

  • 📧 Email: [email protected]
  • 🐛 Issues: GitHub Issues tab
  • 💬 Discussions: GitHub Discussions

Acknowledgments

Built with ❤️ using:


Last Updated: February 13, 2026 Version: 0.0.1

About

it's about an e-commerce backend for a store that are sealing sport clothes

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages