Skip to content

DevBassel/e-store-API

Repository files navigation

πŸ›’ E-Commerce API

A robust, scalable RESTful API for a full-featured e-commerce platform, built with NestJS, TypeORM, and PostgreSQL. Provides complete backend services including authentication, product management, shopping cart, order processing, Stripe payments, reviews, favourites, coupons, and more.

πŸ“– Live Swagger Docs


πŸ“‹ Table of Contents


✨ Features

Feature Description
πŸ” Authentication Register, login, logout, and token refresh with JWT + Passport.js
πŸ”‘ Password Management Forgot password, reset via email OTP, and authenticated password change
πŸ‘₯ User Management Profile view/update, admin user listing, role-based access (User, Manager, Admin)
πŸ“¦ Products Full CRUD with image upload (Cloudinary), pagination, filtering by category/price/search
πŸ—‚οΈ Categories Create, list, update, and delete product categories
πŸ›’ Cart Add/remove/update items, view cart β€” all scoped to the authenticated user
πŸ“‹ Orders Place orders from cart, view order history, filter by status, cancel orders
πŸ’³ Stripe Payments Create payment intents for orders, Stripe webhook for payment confirmation
⭐ Reviews Create, read, update, and delete product reviews with pagination
❀️ Favourites Add/remove products to a personal wishlist
🎟️ Coupons Admin-managed discount coupons with CRUD operations
πŸ“§ Email Service Transactional emails (password reset) via Nodemailer
☁️ Image Hosting Cloudinary integration for product image upload and CDN delivery
πŸ“– API Docs Auto-generated interactive Swagger/OpenAPI documentation
βœ… Validation Request body validation with class-validator and DTO whitelisting
🐳 Docker Dockerfile and docker-compose for containerized deployment with PostgreSQL

πŸ› οΈ Tech Stack

Technology Version Purpose
NestJS 10.x Progressive Node.js framework
TypeORM 0.3.x ORM for PostgreSQL
PostgreSQL Latest Relational database
Passport.js β€” Authentication middleware
JWT β€” Token-based auth (access + refresh tokens)
Swagger/OpenAPI 7.x Interactive API documentation
Stripe 16.x Payment processing + webhooks
Cloudinary 2.x Image upload and CDN
Nodemailer 6.x Email delivery
class-validator 0.14.x DTO validation
bcrypt 5.x Password hashing
Docker β€” Containerization

πŸ›οΈ Architecture

The API follows NestJS's modular architecture. Each domain feature is a self-contained module with its own controller, service, DTOs, entities, and guards.

                      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                      β”‚   Client / Frontend  β”‚
                      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                 β”‚  HTTP
                      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                      β”‚   NestJS Application β”‚
                      β”‚   (Global Prefix:    β”‚
                      β”‚    /api/v1)           β”‚
                      β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
                      β”‚     Middleware       β”‚
                      β”‚  β”Œβ”€ CORS            β”‚
                      β”‚  β”œβ”€ ValidationPipe   β”‚
                      β”‚  └─ ClassSerializer  β”‚
                      β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
                      β”‚      Modules         β”‚
                      β”‚  β”Œβ”€β”€ Auth + JWT      β”‚
                      β”‚  β”œβ”€β”€ User            β”‚
                      β”‚  β”œβ”€β”€ Products        β”‚
                      β”‚  β”œβ”€β”€ Categories      β”‚
                      β”‚  β”œβ”€β”€ Cart            β”‚
                      β”‚  β”œβ”€β”€ Order           β”‚
                      β”‚  β”œβ”€β”€ Payment (Stripe)β”‚
                      β”‚  β”œβ”€β”€ Review          β”‚
                      β”‚  β”œβ”€β”€ Favourite       β”‚
                      β”‚  β”œβ”€β”€ Coupons         β”‚
                      β”‚  β”œβ”€β”€ Cloudinary      β”‚
                      β”‚  └── Email           β”‚
                      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                 β”‚
               β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
               β”‚                 β”‚                  β”‚
        β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”
        β”‚  PostgreSQL  β”‚  β”‚  Cloudinary  β”‚  β”‚    Stripe    β”‚
        β”‚  (TypeORM)   β”‚  β”‚  (Images)    β”‚  β”‚  (Payments)  β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“ Project Structure

backend/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main.ts                          # App bootstrap, CORS, Swagger, global pipes
β”‚   β”œβ”€β”€ app.module.ts                    # Root module β€” imports all feature modules
β”‚   β”œβ”€β”€ decorator/                       # Custom decorators
β”‚   β”‚   β”œβ”€β”€ GetUser.decorator.ts         # Extract user from JWT payload
β”‚   β”‚   β”œβ”€β”€ role.decorator.ts            # @Roles() decorator for RBAC
β”‚   β”‚   └── queryArray.decorator.ts      # @ApiQueryArray() for Swagger docs
β”‚   β”œβ”€β”€ utils/                           # Shared utility functions
β”‚   └── modules/
β”‚       β”œβ”€β”€ auth/                        # Authentication & authorization
β”‚       β”‚   β”œβ”€β”€ auth.controller.ts       # POST /register, /login, /refresh, /log-out
β”‚       β”‚   β”œβ”€β”€ auth.service.ts          # Auth business logic, bcrypt, JWT signing
β”‚       β”‚   β”œβ”€β”€ password.controller.ts   # POST /forgot-password, /reset-*-password
β”‚       β”‚   β”œβ”€β”€ password.service.ts      # Password reset flow with email OTP
β”‚       β”‚   β”œβ”€β”€ dto/                     # LoginDto, ForgotPasswordDto, ResetPasswordDto, JwtPayload
β”‚       β”‚   β”œβ”€β”€ enums/
β”‚       β”‚   β”‚   └── role.enum.ts         # Role.USER | Role.MANAGER | Role.ADMIN
β”‚       β”‚   β”œβ”€β”€ guards/
β”‚       β”‚   β”‚   β”œβ”€β”€ jwt.guard.ts         # Passport JWT guard
β”‚       β”‚   β”‚   └── role.guard.ts        # Role-based access guard
β”‚       β”‚   └── strategy/               # Passport JWT strategy
β”‚       β”‚
β”‚       β”œβ”€β”€ user/                        # User management
β”‚       β”‚   β”œβ”€β”€ user.controller.ts       # GET /users, /users/profile, /users/find/:id
β”‚       β”‚   β”œβ”€β”€ user.service.ts          # User CRUD, profile operations
β”‚       β”‚   β”œβ”€β”€ dto/                     # CreateUserDto, UpdateProfileDto
β”‚       β”‚   └── entities/               # User entity (TypeORM)
β”‚       β”‚
β”‚       β”œβ”€β”€ products/                    # Product catalog
β”‚       β”‚   β”œβ”€β”€ products.controller.ts   # CRUD + pagination, filtering, search, image upload
β”‚       β”‚   β”œβ”€β”€ products.service.ts      # Product business logic
β”‚       β”‚   β”œβ”€β”€ dto/                     # CreateProductDto, UpdateProductDto
β”‚       β”‚   └── entities/               # Product entity
β”‚       β”‚
β”‚       β”œβ”€β”€ categories/                  # Product categories
β”‚       β”‚   β”œβ”€β”€ categories.controller.ts # Full CRUD for categories
β”‚       β”‚   β”œβ”€β”€ categories.service.ts
β”‚       β”‚   β”œβ”€β”€ dto/                     # CreateCategoryDto, UpdateCategoryDto
β”‚       β”‚   └── entities/               # Category entity
β”‚       β”‚
β”‚       β”œβ”€β”€ cart/                         # Shopping cart
β”‚       β”‚   β”œβ”€β”€ cart.controller.ts       # CRUD β€” all routes require JWT auth
β”‚       β”‚   β”œβ”€β”€ cart.service.ts          # Cart business logic (user-scoped)
β”‚       β”‚   β”œβ”€β”€ dto/                     # CreateCartDto, UpdateCartItemDto
β”‚       β”‚   └── entities/               # Cart / CartItem entities
β”‚       β”‚
β”‚       β”œβ”€β”€ order/                       # Order processing
β”‚       β”‚   β”œβ”€β”€ order.controller.ts      # Create, list (paginated + status filter), cancel
β”‚       β”‚   β”œβ”€β”€ order.service.ts         # Order workflow, status management
β”‚       β”‚   β”œβ”€β”€ dto/                     # CreateOrderDto, UpdateOrderDto
β”‚       β”‚   β”œβ”€β”€ entities/               # Order entity
β”‚       β”‚   └── enums/
β”‚       β”‚       └── order-status.enum.ts # inProcess | shipped | cancel | success
β”‚       β”‚
β”‚       β”œβ”€β”€ paymeny/                     # Stripe payment integration
β”‚       β”‚   β”œβ”€β”€ paymeny.controller.ts    # POST /payments/create, /payments/webhook
β”‚       β”‚   β”œβ”€β”€ paymeny.service.ts       # Stripe payment intent creation + webhook handler
β”‚       β”‚   └── paymeny.module.ts
β”‚       β”‚
β”‚       β”œβ”€β”€ review/                      # Product reviews
β”‚       β”‚   β”œβ”€β”€ review.controller.ts     # CRUD + paginated listing per product
β”‚       β”‚   β”œβ”€β”€ review.service.ts
β”‚       β”‚   β”œβ”€β”€ dto/                     # CreateReviewDto, UpdateReviewDto
β”‚       β”‚   └── entities/               # Review entity
β”‚       β”‚
β”‚       β”œβ”€β”€ favourite/                   # Wishlist / Favourites
β”‚       β”‚   β”œβ”€β”€ favourite.controller.ts  # Add, list, remove β€” user-scoped
β”‚       β”‚   β”œβ”€β”€ favourite.service.ts
β”‚       β”‚   β”œβ”€β”€ dto/                     # CreateFavouriteDto
β”‚       β”‚   └── entities/               # Favourite entity
β”‚       β”‚
β”‚       β”œβ”€β”€ coupons/                     # Discount coupons (Admin only)
β”‚       β”‚   β”œβ”€β”€ coupons.controller.ts    # Full CRUD β€” Admin role required
β”‚       β”‚   β”œβ”€β”€ coupons.service.ts
β”‚       β”‚   β”œβ”€β”€ dto/                     # CreateCouponDto, UpdateCouponDto
β”‚       β”‚   └── entities/               # Coupon entity
β”‚       β”‚
β”‚       β”œβ”€β”€ cloudinary/                  # Image upload service
β”‚       β”‚   └── cloudinary.module.ts     # Cloudinary SDK configuration
β”‚       β”‚
β”‚       β”œβ”€β”€ email/                       # Email service
β”‚       β”‚   └── ...                      # Nodemailer transporter (Gmail/SMTP)
β”‚       β”‚
β”‚       β”œβ”€β”€ jwt/                         # Global JWT module
β”‚       β”‚   └── jwt.module.ts            # JwtModule.registerAsync (global)
β”‚       β”‚
β”‚       └── DB/                          # Database configuration
β”‚           β”œβ”€β”€ DB.module.ts             # TypeOrmModule.forRootAsync
β”‚           β”œβ”€β”€ data-source.ts           # TypeORM DataSource for CLI migrations
β”‚           └── migrations/             # Database migration files
β”‚
β”œβ”€β”€ test/                                # E2E tests
β”œβ”€β”€ Dockerfile                           # Node 20 multi-stage build
β”œβ”€β”€ docker-compose.yml                   # App + PostgreSQL services
β”œβ”€β”€ .env.example                         # Environment variable template
β”œβ”€β”€ tsconfig.json
└── package.json

πŸš€ Getting Started

Prerequisites

  • Node.js β‰₯ 20
  • pnpm (recommended) or npm
  • PostgreSQL β‰₯ 14 (or use Docker)
  • A Stripe account (for payment features)
  • A Cloudinary account (for image uploads)
  • A Gmail account or SMTP service (for emails)

Installation

# Clone the repository
git clone https://github.com/DevBassel/e-store-API.git
cd backend

# Install dependencies
pnpm install

# Copy and configure environment variables
cp .env.example .env
# Edit .env with your credentials (see Environment Variables section)

# Start in development mode (hot-reload)
pnpm run start:dev

The API server starts on http://localhost:4000 (or your configured PORT). Swagger documentation is available at http://localhost:4000/api.

Seed the Database

Populate the database with sample data using Faker.js:

pnpm run seeding

πŸ” Environment Variables

Create a .env file in the project root using .env.example as a template:

# Server Configuration
PORT=4000
HOST=http://localhost:4000
NODE_ENV=dev                              # Options: dev, prod

# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=e_commerce
DB_USERNAME=postgres
DB_PASSWORD=root
DB_Sync=true                              # Auto-sync schema (dev only!)

# JWT Configuration
JWT_KEY=your_jwt_secret_key

# Email Configuration (Gmail App Password or SMTP)
EMAIL_USER=your_email@gmail.com
EMAIL_SK=your_email_app_password

# Cloudinary Configuration
CLOUD_NAME=your_cloudinary_cloud_name
CLOUD_API_KEY=your_cloudinary_api_key
CLOUD_API_SECRET=your_cloudinary_api_secret

# Stripe Configuration
STRIPE_SK=your_stripe_secret_key
STRIPE_WEEBHOOK_SK=your_stripe_webhook_secret

⚠️ Warning: Set DB_Sync=false in production. Use migrations instead.


πŸ“– API Reference

All endpoints are prefixed with /api/v1. Interactive documentation is available via Swagger at /api.

Auth (/api/v1/auth)

Method Endpoint Auth Description
POST /auth/register ❌ Register a new user
POST /auth/login ❌ Login and receive JWT tokens
POST /auth/refresh ❌ Refresh access token
POST /auth/log-out πŸ”’ Logout (invalidate refresh token)

Password Management (/api/v1/auth)

Method Endpoint Auth Description
POST /auth/forgot-password ❌ Send password reset email
POST /auth/reset-forgot-password ❌ Reset password via email token
POST /auth/reset-password πŸ”’ Change password (authenticated)

Users (/api/v1/users)

Method Endpoint Auth Description
GET /users πŸ”’ Admin List all users (paginated)
GET /users/profile πŸ”’ Get authenticated user's profile
PATCH /users/profile πŸ”’ Update profile
GET /users/find/:userId πŸ”’ Find a user by ID

Products (/api/v1/products)

Method Endpoint Auth Description
POST /products πŸ”’ Admin/Manager Create product (multipart/form-data with image)
GET /products ❌ List products (paginated, filterable)
GET /products/:id ❌ Get product details
PATCH /products/:id πŸ”’ Update product
DELETE /products/:id πŸ”’ Admin/Manager Delete product

Query Parameters for GET /products:

Param Type Default Description
page number 1 Page number
limit number 10 Items per page
category string β€” Filter by category
min number 0 Minimum price
max number 1,000,000 Maximum price
s string β€” Search term

Categories (/api/v1/categories)

Method Endpoint Auth Description
POST /categories ❌ Create a category
GET /categories ❌ List all categories
GET /categories/:id ❌ Get category by ID
PATCH /categories/:id ❌ Update category
DELETE /categories/:id ❌ Delete category

Cart (/api/v1/cart)

Method Endpoint Auth Description
POST /cart πŸ”’ Add item to cart
GET /cart πŸ”’ Get user's cart
GET /cart/:id πŸ”’ Get specific cart item
PATCH /cart/:id πŸ”’ Update cart item quantity
DELETE /cart/:id πŸ”’ Remove item from cart

Orders (/api/v1/orders)

Method Endpoint Auth Description
POST /orders πŸ”’ Create order from cart
GET /orders πŸ”’ List orders (paginated, status filter)
GET /orders/:id πŸ”’ Get order details
GET /orders/me πŸ”’ Get current user's orders
PATCH /orders/:id πŸ”’ Update order
DELETE /orders/:id πŸ”’ Cancel order

Order Statuses: inProcess β†’ shipped β†’ success | cancel

Payments (/api/v1/payments)

Method Endpoint Auth Description
POST /payments/create πŸ”’ Create Stripe payment intent for an order
POST /payments/webhook β€” Stripe webhook endpoint (signature verified)

Reviews (/api/v1/reviews)

Method Endpoint Auth Description
POST /reviews πŸ”’ Create a review
GET /reviews/:productId ❌ List reviews for a product (paginated)
GET /reviews/:id/view ❌ Get single review
PATCH /reviews/:id πŸ”’ Update a review
DELETE /reviews/:id πŸ”’ Delete a review

Favourites (/api/v1/favourite)

Method Endpoint Auth Description
POST /favourite πŸ”’ Add product to favourites
GET /favourite πŸ”’ List user's favourites
GET /favourite/:id πŸ”’ Get specific favourite
DELETE /favourite/:id πŸ”’ Remove from favourites

Coupons (/api/v1/coupons)

Method Endpoint Auth Description
POST /coupons πŸ”’ Admin Create coupon
GET /coupons πŸ”’ Admin List coupons (paginated)
GET /coupons/:id πŸ”’ Admin Get coupon details
PATCH /coupons/:id πŸ”’ Admin Update coupon
DELETE /coupons/:id πŸ”’ Admin Delete coupon

πŸ›‘οΈ Authorization & Roles

The API uses a role-based access control (RBAC) system with three roles:

Role Value Permissions
User user Default role. Can manage own cart, orders, reviews, favourites, and profile
Manager manager Can create, update, and delete products
Admin admin Full access β€” user management, product management, coupon management

Guards applied:

  • JwtGuard β€” Validates the Bearer JWT token from the Authorization header
  • RoleGuard β€” Checks the user's role against the @Roles() decorator on the endpoint

πŸ—ƒοΈ Database

TypeORM Configuration

The database connection is configured via environment variables and managed by TypeORM:

  • Entities are auto-discovered from each module's entities/ directory
  • Synchronization (DB_Sync=true) auto-creates/updates tables from entities (dev only)
  • Migrations are stored in src/modules/DB/migrations/

Migration Commands

# Generate a migration from entity changes
pnpm run migration:generate -- src/modules/DB/migrations/MigrationName

# Run pending migrations
pnpm run migration:run

# Revert the last migration
pnpm run migration:revert

🐳 Docker

Docker Compose (Recommended)

Spins up the API and PostgreSQL together:

docker-compose up -d

Services:

Service Image Port
app Built from Dockerfile 3000
postgres postgres:latest 5432

Standalone Docker Build

# Build the image
docker build -t e-commerce-api .

# Run the container
docker run -p 4000:4000 --env-file .env e-commerce-api

πŸ§ͺ Testing

# Unit tests
pnpm run test

# Watch mode
pnpm run test:watch

# Coverage report
pnpm run test:cov

# E2E tests
pnpm run test:e2e

# Debug tests
pnpm run test:debug

πŸ“œ Scripts

Script Command Description
start:dev pnpm run start:dev Development server with hot-reload
start:prod pnpm run start:prod Production server (compiled JS)
build pnpm run build Compile TypeScript via NestJS CLI
seeding pnpm run seeding Seed database with sample data
migration:generate pnpm run migration:generate Generate new migration
migration:run pnpm run migration:run Execute pending migrations
migration:revert pnpm run migration:revert Revert last migration
webhook pnpm run webhook Forward Stripe webhooks locally
test pnpm run test Run unit tests
test:e2e pnpm run test:e2e Run end-to-end tests
test:cov pnpm run test:cov Generate coverage report
lint pnpm run lint Lint and auto-fix with ESLint
format pnpm run format Format code with Prettier

πŸ“„ License

This project is UNLICENSED β€” private use only.

Releases

No releases published

Packages

 
 
 

Contributors

Languages