A robust, scalable RESTful API built with NestJS for e-commerce applications. Features include user authentication, product management, order processing, and comprehensive API documentation.
- Authentication & Authorization: JWT-based authentication with role-based access control (Admin/Customer)
- User Management: User registration and login
- Product Management: CRUD operations for products with categories and inventory tracking
- Order Processing: Complete order lifecycle management with order items
- Database: PostgreSQL with Prisma ORM for type-safe database operations
- API Documentation: Auto-generated Swagger documentation
- Docker Support: Containerized development and production environments
- Security: Password hashing, input validation, and error handling
- Testing: Unit and integration tests with Jest
This project follows a modular architecture pattern with clear separation of concerns:
src/
├── auth/ # Authentication module
├── users/ # User management module
├── products/ # Product management module
├── orders/ # Order processing module
├── common/ # Shared utilities, decorators, filters
├── prisma/ # Database configuration
└── main.ts # Application entry point
- Framework: NestJS - Progressive Node.js framework
- Database: PostgreSQL with Prisma ORM
- Authentication: JWT
- Validation: class-validator & class-transformer
- Documentation: Swagger with @nestjs/swagger
- Testing: Jest with Supertest
- Development: TypeScript, ESLint, Prettier
- Node.js (v18 or higher)
- PostgreSQL (v15 or higher)
- Docker & Docker Compose (optional)
git clone https://github.com/Sanoy24/e-commerce-api.git
cd e-commerce-apinpm installCreate a .env file in the root directory:
# Database
DATABASE_URL="postgresql://<user>:<your password>@<host>:5432/ecommerce_db"
or
DATABASE_URL="postgresql://postgres:postgres@db:5432/ecommerce_db" for docker setup
# Application
PORT=3000
# JWT
JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRES_IN=7d
SALT_VALUE=10
# Generate Prisma client
npx prisma generate
# Run database migrations
npx prisma migrate dev
# Seed the database (optional)
npx prisma db seednpm run start:devnpm run build
npm run start:prod# Start all services (API + PostgreSQL)
docker-compose up -d
# View logs
docker-compose logs -f api
# Stop services
docker-compose down- When using Docker for setup, the application automatically seeds two users into the database:
-
Admin user
{ "email": "admin@example.com", "password": "Admin@123", "username": "admin", "role": "ADMIN" } -
Customer user
{
"email": "test@example.com",
"password": "Pass@123",
"username": "user1",
"role": "CUSTOMER"
}Once the application is running, access the interactive API documentation:
- Swagger UI: http://localhost:3000/api/v1/docs
- API Base URL: http://localhost:3000/api/v1
- Register:
POST /api/v1/auth/register - Login:
POST /api/v1/auth/login - Use Token: Include
Authorization: Bearer <token>in subsequent requests
GET /healthcheck- check if the server and db is healthy
POST /auth/register- Register new userPOST /auth/login- User login
GET /products- Get all productsGET /products/:id- Get product by IDPOST /products- Create product (Admin only)PUT /products/:id- Update product (Admin only)DELETE /products/:id- Delete product (Admin only)
GET /orders- Get user ordersPOST /orders- Create new order
POST /uploads- upload product image
# Unit tests
npm run test
# Test coverage
npm run test:cov
# End-to-end tests
npm run test:e2e
# Watch mode
npm run test:watch- Prepare database (only needed for tests that hit the DB):
- Start local Postgres or run
docker compose up -d db. - Ensure
.envhas a validDATABASE_URL, e.g.postgresql://postgres:postgres@localhost:5432/ecommerce_db.
- Start local Postgres or run
- Commands:
- Unit tests:
npm run test - Coverage:
npm run test:cov - E2E tests:
npm run test:e2e - Watch mode:
npm run test:watch
- Unit tests:
- Bring up the stack:
docker compose up -d. - Ensure
.envuses the Compose network host for DB:DATABASE_URL="postgresql://postgres:postgres@db:5432/ecommerce_db"
- Inside the running API container:
- Unit tests:
docker compose exec api npm run test - E2E tests:
docker compose exec api npm run test:e2e
- Unit tests:
- One-off test container (clean environment):
- Unit tests:
docker compose run --rm api sh -c "npm ci && npm run test" - E2E tests:
docker compose run --rm api sh -c "npm ci && npm run test:e2e"
- Unit tests:
- Optional DB reset/seed before E2E:
docker compose exec api npx prisma migrate reset --forcedocker compose exec api npx prisma db seed
Notes:
- The Compose service is named
apiand depends on thedbservice being healthy. - The stack seeds the database on startup via
npx prisma db seedin the API command.
id(UUID, Primary Key)username(String, Unique)email(String, Unique)password(String, Hashed)role(Enum: ADMIN, CUSTOMER)createdAt,updatedAt(Timestamps)
id(UUID, Primary Key)name(String)description(String, Optional)price(Float)stock(Integer)category(String, Optional)userId(Foreign Key to User)
id(UUID, Primary Key)userId(Foreign Key to User)description(String, Optional)totalPrice(Float)status(String, Default: "pending")createdAt,updatedAt(Timestamps)
id(UUID, Primary Key)orderId(Foreign Key to Order)productId(Foreign Key to Product)quantity(Integer, Default: 1)
- Password Hashing: Bcrypt for secure password storage
- JWT Authentication: Stateless authentication
- Input Validation: Comprehensive validation using class-validator
- Error Handling: Centralized error handling with custom filters
- CORS Protection: Configurable CORS policies
- Rate Limiting: Ready for rate limiting implementation
-
Build the application:
npm run build
-
Set production environment variables
-
Run migrations:
npx prisma migrate deploy
-
Start the application:
npm run start:prod
# Build and run with Docker Compose
docker-compose -f docker-compose.yml up -d