Skip to content

Repository files navigation

E-Commerce API

A production-grade RESTful API built with NestJS, TypeORM, and PostgreSQL. Implements a complete e-commerce backend with JWT authentication, role-based access control, full CRUD for all resources, and comprehensive test coverage.

Table of Contents


Features

Module Capabilities
Auth Register, login, JWT access + refresh tokens, logout
Users Profile management, admin user CRUD, role management
Categories Hierarchical categories with slugs, nested parent/child
Products Full CRUD, search, price filtering, pagination, sorting, average rating
Cart Per-user cart, add/update/remove items, real-time stock validation
Orders Create from cart, full order lifecycle, automatic stock management
Reviews Product reviews, automatic rating recalculation

Cross-cutting concerns:

  • Global exception filter with structured error responses
  • Global response envelope ({ success, data, timestamp })
  • Request logging interceptor
  • ClassSerializerInterceptor ? passwords never leak in responses
  • Rate limiting (throttler)
  • Helmet security headers
  • CORS
  • Input validation via class-validator + class-transformer
  • Swagger / OpenAPI documentation

Tech Stack

  • Framework: NestJS v11
  • Language: TypeScript 5
  • ORM: TypeORM with PostgreSQL
  • Auth: Passport.js ? passport-jwt, JWT access + refresh tokens
  • Password hashing: bcrypt (cost factor 12)
  • Validation: class-validator + class-transformer
  • API Docs: Swagger (@nestjs/swagger)
  • Testing: Jest + Supertest

Project Structure

src/
??? main.ts                        # App bootstrap, Swagger setup
??? app.module.ts                  # Root module
??? config/                        # Config factories (app, db, jwt)
??? common/
?   ??? filters/                   # Global exception filter
?   ??? interceptors/              # Transform + logging interceptors
?   ??? decorators/                # @CurrentUser decorator
??? auth/
?   ??? strategies/                # JWT + JWT refresh strategies
?   ??? guards/                    # JwtAuthGuard, JwtRefreshGuard, RolesGuard
?   ??? decorators/                # @Roles, @Public
?   ??? dto/                       # RegisterDto, LoginDto, RefreshTokenDto
?   ??? auth.service.ts
?   ??? auth.service.spec.ts
?   ??? auth.controller.ts
??? users/
?   ??? entities/user.entity.ts    # User entity with bcrypt hook
?   ??? dto/                       # CreateUserDto, UpdateUserDto
?   ??? users.service.ts
?   ??? users.service.spec.ts
?   ??? users.controller.ts
??? categories/
?   ??? entities/category.entity.ts
?   ??? dto/
?   ??? categories.service.ts
?   ??? categories.service.spec.ts
?   ??? categories.controller.ts
??? products/
?   ??? entities/product.entity.ts
?   ??? dto/                       # CreateProductDto, UpdateProductDto, ProductQueryDto
?   ??? products.service.ts
?   ??? products.service.spec.ts
?   ??? products.controller.ts
??? cart/
?   ??? entities/                  # Cart, CartItem
?   ??? dto/
?   ??? cart.service.ts
?   ??? cart.controller.ts
??? orders/
?   ??? entities/                  # Order, OrderItem
?   ??? dto/
?   ??? orders.service.ts
?   ??? orders.controller.ts
??? reviews/
    ??? entities/review.entity.ts
    ??? dto/
    ??? reviews.service.ts
    ??? reviews.service.spec.ts
    ??? reviews.controller.ts
test/
??? app.e2e-spec.ts               # End-to-end tests
??? jest-e2e.json

Getting Started

Prerequisites

  • Node.js >= 18
  • PostgreSQL >= 14
  • npm >= 9

Installation

# Clone and install
git clone <repo-url>
cd e-commerce-api
npm install

# Copy and configure environment
cp .env.example .env
# Edit .env with your DB credentials and JWT secrets

Create the Database

CREATE DATABASE ecommerce_db;

Note: With DB_SYNCHRONIZE=true, TypeORM automatically creates/updates all tables on startup. Use migrations for production.

Run the Server

# Development (watch mode)
npm run start:dev

# Production build
npm run build
npm run start:prod

The API will be available at:

  • Base URL: http://localhost:3000/api/v1
  • Swagger UI: http://localhost:3000/api/docs

Environment Variables

Variable Description Default
NODE_ENV Environment development
PORT HTTP port 3000
DB_HOST PostgreSQL host localhost
DB_PORT PostgreSQL port 5432
DB_USERNAME DB user postgres
DB_PASSWORD DB password ?
DB_NAME Database name ecommerce_db
DB_SYNCHRONIZE Auto-sync schema true
DB_LOGGING Log SQL queries false
JWT_SECRET Access token secret ?
JWT_EXPIRATION Access token TTL 15m
JWT_REFRESH_SECRET Refresh token secret ?
JWT_REFRESH_EXPIRATION Refresh token TTL 7d
THROTTLE_TTL Rate limit window (s) 60
THROTTLE_LIMIT Max requests per window 100

API Reference

All endpoints are prefixed with /api/v1. Full interactive documentation is available at /api/docs.

Auth

Method Endpoint Auth Description
POST /auth/register Public Register a new user
POST /auth/login Public Login, returns access + refresh tokens
POST /auth/refresh Refresh token Get new token pair
POST /auth/logout Bearer Logout (client discards tokens)

Users

Method Endpoint Auth Description
GET /users Admin List all users
GET /users/me Bearer Get own profile
PATCH /users/me Bearer Update own profile
GET /users/:id Admin Get user by ID
PATCH /users/:id Admin Update user by ID
DELETE /users/:id Admin Delete user

Categories

Method Endpoint Auth Description
POST /categories Admin Create category
GET /categories Public List all categories
GET /categories/:id Public Get category by ID
PUT /categories/:id Admin Update category
DELETE /categories/:id Admin Delete category

Products

Method Endpoint Auth Description
POST /products Admin Create product
GET /products Public List (search, filter, paginate, sort)
GET /products/:id Public Get product by ID
PUT /products/:id Admin Update product
DELETE /products/:id Admin Delete product

Query parameters for GET /products:

Param Type Description
page number Page number (default: 1)
limit number Items per page (default: 12, max: 100)
search string Full-text search on name/description
categoryId UUID Filter by category
minPrice number Minimum price
maxPrice number Maximum price
isFeatured boolean Filter featured products
sortBy string price, createdAt, name, averageRating
sortOrder string ASC or DESC

Cart

Method Endpoint Auth Description
GET /cart Bearer Get user's cart
POST /cart/items Bearer Add item to cart
PUT /cart/items/:itemId Bearer Update item quantity
DELETE /cart/items/:itemId Bearer Remove item from cart
DELETE /cart Bearer Clear entire cart

Orders

Method Endpoint Auth Description
POST /orders Bearer Create order from cart
GET /orders Bearer List orders (admin: all; customer: own)
GET /orders/:id Bearer Get order by ID
PATCH /orders/:id/status Bearer Update status (admin: any; customer: cancel only)

Order Status Flow: pending ? confirmed ? processing ? shipped ? delivered Cancellable from pending or confirmed. Cancellation automatically restores stock.

Reviews

Method Endpoint Auth Description
POST /reviews Bearer Create review (one per product per user)
GET /reviews/product/:productId Public Get reviews for a product
PATCH /reviews/:id Bearer Update own review
DELETE /reviews/:id Bearer Delete review (admin can delete any)

Authentication

The API uses JWT Bearer tokens.

  1. Register or login to receive accessToken and refreshToken
  2. Include the access token in all protected requests:
    Authorization: Bearer <accessToken>
    
  3. When the access token expires (15 min), use the refresh token:
    POST /api/v1/auth/refresh
    { "refreshToken": "<your-refresh-token>" }
    

Running Tests

# Unit tests
npm test

# Unit tests with coverage
npm run test:cov

# Watch mode
npm run test:watch

# E2E tests (requires running PostgreSQL)
npm run test:e2e

Test Coverage

Unit tests cover:

  • AuthService ? register, login, token refresh edge cases
  • UsersService ? CRUD, conflict detection
  • ProductsService ? CRUD, pagination, slug generation
  • CategoriesService ? CRUD, slug generation
  • ReviewsService ? create, ownership enforcement, rating recalculation

Database

Entity Relationships

User ???????????????????? Cart (1:1)
User ???????????????????? Order (1:N)
User ???????????????????? Review (1:N)
Category ???????????????? Product (1:N)
Category ???????????????? Category (self-referential, parent/child)
Product ????????????????? Review (1:N)
Cart ????????????????????? CartItem (1:N)
CartItem ???????????????? Product (N:1)
Order ???????????????????? OrderItem (1:N)
OrderItem ??????????????? Product (N:1)

Schema Sync vs Migrations

  • Development: DB_SYNCHRONIZE=true auto-syncs the schema
  • Production: Set DB_SYNCHRONIZE=false and use TypeORM migrations:
    npx typeorm migration:generate -n MigrationName
    npx typeorm migration:run

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages