Skip to content

chadiegil/ecommerce-api

Repository files navigation

E-commerce API

A comprehensive RESTful API for an e-commerce platform built with Node.js, TypeScript, Express.js, Prisma ORM, and MongoDB.

Features

  • JWT-based authentication and authorization
  • Role-based access control (Admin/Customer)
  • Complete product management
  • Shopping cart functionality
  • Order processing with stock management
  • Request logging and validation
  • Structured error handling
  • Dockerized setup for easy deployment

Tech Stack

  • Runtime: Node.js
  • Language: TypeScript
  • Framework: Express.js
  • Database: MongoDB
  • ORM: Prisma
  • Authentication: JWT (JSON Web Tokens)
  • Validation: Zod
  • Logging: Morgan
  • Containerization: Docker & Docker Compose

Project Structure

ecommerce-api/
├── src/
│   ├── controllers/      # Request handlers
│   ├── routes/           # API routes
│   ├── services/         # Business logic
│   ├── middleware/       # Custom middleware
│   ├── validators/       # Zod validation schemas
│   ├── utils/            # Utility functions
│   ├── types/            # TypeScript types
│   └── index.ts          # Application entry point
├── prisma/
│   ├── schema.prisma     # Database schema
│   └── seed.ts           # Database seeding script
├── Dockerfile            # Docker configuration
├── docker-compose.yml    # Docker Compose configuration
├── tsconfig.json         # TypeScript configuration
├── package.json          # Dependencies
└── .env                  # Environment variables

Prerequisites

  • Docker and Docker Compose installed on your system
  • OR Node.js 18+ and MongoDB installed locally

Getting Started with Docker (Recommended)

1. Clone the repository

git clone <repository-url>
cd ecommerce-api

2. Configure environment variables

The .env file is already created with default values. You can modify it if needed:

DATABASE_URL="mongodb://mongodb:27017/ecommerce?authSource=admin"
JWT_SECRET="your-super-secret-jwt-key-change-this-in-production"
JWT_EXPIRES_IN="7d"
PORT=3000
NODE_ENV="development"

3. Build and run with Docker Compose

docker-compose up --build

This command will:

  • Start MongoDB container
  • Build and start the API container
  • Run Prisma migrations
  • Make the API available at http://localhost:3000

4. Seed the database (Optional)

In a new terminal, run:

docker-compose exec api npm run seed

This will populate the database with sample data including:

  • 3 users (1 admin, 2 customers)
  • 10 products across different categories
  • Sample cart items and orders

Test Credentials:

  • Admin: admin@example.com / password123
  • Customer 1: john@example.com / password123
  • Customer 2: jane@example.com / password123

Getting Started without Docker

1. Install dependencies

npm install

2. Configure environment variables

Update the .env file with your local MongoDB connection:

DATABASE_URL="mongodb://localhost:27017/ecommerce"
JWT_SECRET="your-super-secret-jwt-key-change-this-in-production"
JWT_EXPIRES_IN="7d"
PORT=3000
NODE_ENV="development"

3. Generate Prisma Client

npm run prisma:generate

4. Push database schema

npm run prisma:push

5. Seed the database (Optional)

npm run seed

6. Start the development server

npm run dev

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

API Endpoints

Authentication

Method Endpoint Description Auth Required
POST /api/auth/register Register new user No
POST /api/auth/login Login user No
GET /api/auth/profile Get user profile Yes
PUT /api/auth/profile Update user profile Yes

Products

Method Endpoint Description Auth Required Role
GET /api/products Get all products No -
GET /api/products/:id Get product by ID No -
GET /api/products/category/:category Get products by category No -
POST /api/products Create product Yes Admin
PUT /api/products/:id Update product Yes Admin
DELETE /api/products/:id Delete product Yes Admin

Cart

Method Endpoint Description Auth Required
POST /api/cart Add item to cart Yes
GET /api/cart Get user's cart Yes
DELETE /api/cart/:id Remove item from cart Yes
DELETE /api/cart Clear cart Yes

Orders

Method Endpoint Description Auth Required Role
POST /api/orders Create order from cart items Yes Customer
GET /api/orders Get user's orders Yes Customer
GET /api/orders/all Get all orders Yes Admin
GET /api/orders/:id Get order by ID Yes Customer/Admin
PATCH /api/orders/:id/status Update order status Yes Admin

API Request Examples

Register User

POST /api/auth/register
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "password123",
  "role": "CUSTOMER"
}

Login

POST /api/auth/login
Content-Type: application/json

{
  "email": "john@example.com",
  "password": "password123"
}

Create Product (Admin)

POST /api/products
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "Laptop",
  "description": "High-performance laptop",
  "price": 1299.99,
  "stock": 50,
  "category": "Electronics"
}

Add to Cart

POST /api/cart
Authorization: Bearer <token>
Content-Type: application/json

{
  "productId": "product_id_here",
  "quantity": 2
}

Create Order

POST /api/orders
Authorization: Bearer <token>
Content-Type: application/json

{
  "items": [
    {
      "productId": "product_id_here",
      "quantity": 1
    }
  ]
}

Testing with Postman

Import the postman_collection.json file into Postman to get a complete collection of API requests.

Steps:

  1. Open Postman
  2. Click Import
  3. Select postman_collection.json
  4. The collection includes variables and automatic token management

Database Models

User

  • id (ObjectId)
  • name (String)
  • email (String, unique)
  • password (String, hashed)
  • role (ADMIN | CUSTOMER)
  • createdAt (DateTime)
  • updatedAt (DateTime)

Product

  • id (ObjectId)
  • name (String)
  • description (String)
  • price (Float)
  • stock (Integer)
  • category (String)
  • createdAt (DateTime)
  • updatedAt (DateTime)

CartItem

  • id (ObjectId)
  • userId (ObjectId, reference to User)
  • productId (ObjectId, reference to Product)
  • quantity (Integer)

Order

  • id (ObjectId)
  • userId (ObjectId, reference to User)
  • totalAmount (Float)
  • status (PENDING | PAID | SHIPPED | COMPLETED | CANCELLED)
  • createdAt (DateTime)
  • updatedAt (DateTime)

OrderItem

  • id (ObjectId)
  • orderId (ObjectId, reference to Order)
  • productId (ObjectId, reference to Product)
  • quantity (Integer)
  • price (Float) - Price at the time of order

Stock Management

When an order is created:

  1. The system validates that sufficient stock exists for all items
  2. Product stock is automatically decremented by the ordered quantity
  3. The user's cart is automatically cleared after successful order creation

Error Handling

The API uses structured error responses:

{
  "success": false,
  "message": "Error description",
  "errors": [] // Optional validation errors
}

HTTP Status Codes:

  • 200: Success
  • 201: Created
  • 400: Bad Request (validation errors)
  • 401: Unauthorized (invalid/missing token)
  • 403: Forbidden (insufficient permissions)
  • 404: Not Found
  • 500: Internal Server Error

Available Scripts

  • npm run dev - Start development server with hot reload
  • npm run build - Build TypeScript to JavaScript
  • npm start - Start production server
  • npm run prisma:generate - Generate Prisma Client
  • npm run prisma:push - Push schema changes to database
  • npm run prisma:studio - Open Prisma Studio (database GUI)
  • npm run seed - Seed database with sample data

Docker Commands

# Build and start containers
docker-compose up --build

# Start containers in detached mode
docker-compose up -d

# Stop containers
docker-compose down

# View logs
docker-compose logs -f api

# Access API container shell
docker-compose exec api sh

# Seed database in Docker
docker-compose exec api npm run seed

# View Prisma Studio (run locally, not in Docker)
npm run prisma:studio

Security Considerations

  • Passwords are hashed using bcryptjs with salt rounds
  • JWT tokens are used for authentication
  • Role-based access control for admin operations
  • Input validation using Zod schemas
  • Environment variables for sensitive data
  • CORS enabled for cross-origin requests

Production Deployment

Before deploying to production:

  1. Change JWT_SECRET to a strong, random value
  2. Update NODE_ENV to production
  3. Configure proper MongoDB connection with authentication
  4. Set up proper logging and monitoring
  5. Configure CORS to allow only specific origins
  6. Use environment-specific .env files
  7. Set up SSL/TLS for HTTPS
  8. Implement rate limiting
  9. Add proper backup strategies for MongoDB

License

ISC

Support

For issues or questions, please open an issue in the repository.

About

API for ecommerce

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published