Skip to content

education-bootcamp/mobile_pos_API

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

13 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Express MongoDB MVC API

A Modern, Scalable RESTful API with JWT Authentication

Node.js Express MongoDB JWT

License PRs Welcome Maintained

Features β€’ Quick Start β€’ API Documentation β€’ Project Structure β€’ Technologies


πŸ“‹ Table of Contents


🎯 Overview

A production-ready Express.js REST API built with MongoDB and following the MVC (Model-View-Controller) architectural pattern. This API features complete JWT authentication, comprehensive CRUD operations, and intelligent inventory management.

Perfect for building e-commerce platforms, order management systems, or any application requiring user authentication and resource management.


✨ Features

πŸ” Authentication

  • βœ… User Registration (Signup)
  • βœ… User Login with JWT
  • βœ… Password Hashing (bcrypt)
  • βœ… Protected Routes
  • βœ… Token Validation

πŸ“¦ Resource Management

  • βœ… Customer CRUD Operations
  • βœ… Product CRUD Operations
  • βœ… Order Management
  • βœ… Inventory Tracking
  • βœ… Auto-calculation

πŸ›‘οΈ Security

  • βœ… JWT Token Authentication
  • βœ… Password Encryption
  • βœ… Request Validation
  • βœ… Error Handling
  • βœ… CORS Enabled

🎨 Code Quality

  • βœ… MVC Architecture
  • βœ… Clean Code Principles
  • βœ… RESTful Best Practices
  • βœ… Modular Structure
  • βœ… Well Documented

πŸš€ Quick Start

Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js (v14 or higher)
  • npm or yarn
  • MongoDB (v4.4 or higher)

Installation

# 1️⃣ Clone the repository
git clone https://github.com/yourusername/express-mongo-mvc.git

# 2️⃣ Navigate to project directory
cd express-mongo-mvc

# 3️⃣ Install dependencies
npm install

# 4️⃣ Configure environment variables
cp .env.example .env
# Edit .env with your configuration

# 5️⃣ Start MongoDB (if not running)
mongod

# 6️⃣ Run the application
npm start

# πŸ”₯ For development with auto-reload
npm run dev

πŸŽ‰ Server is now running at http://localhost:5000


πŸ”§ Environment Variables

Create a .env file in the root directory:

# Server Configuration
PORT=5000
NODE_ENV=development

# Database Configuration
MONGO_URI=mongodb://localhost:27017/express_mvc_db

# JWT Configuration
JWT_SECRET=your_super_secret_jwt_key_change_this_in_production
JWT_EXPIRE=7d

⚠️ Security Note: Never commit your .env file. Always use strong, unique secrets in production!


πŸ“š API Documentation

Base URL

http://localhost:5000/api
πŸ” Authentication Endpoints

1. User Signup

POST /auth/signup

Request Body:

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

Response: 201 Created

{
  "success": true,
  "data": {
    "_id": "507f1f77bcf86cd799439011",
    "name": "John Doe",
    "email": "john@example.com",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }
}

2. User Login

POST /auth/login

Request Body:

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

Response: 200 OK

{
  "success": true,
  "data": {
    "_id": "507f1f77bcf86cd799439011",
    "name": "John Doe",
    "email": "john@example.com",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }
}

3. Get Current User

GET /auth/me

Headers:

Authorization: Bearer YOUR_JWT_TOKEN

Response: 200 OK

{
  "success": true,
  "data": {
    "_id": "507f1f77bcf86cd799439011",
    "name": "John Doe",
    "email": "john@example.com"
  }
}
πŸ‘₯ Customer Endpoints

Note: All customer endpoints require authentication. Include JWT token in Authorization header.

1. Get All Customers

GET /customers

Response: 200 OK

{
  "success": true,
  "count": 2,
  "data": [
    {
      "_id": "507f1f77bcf86cd799439011",
      "name": "Jane Smith",
      "address": "123 Main St, New York, NY",
      "salary": 75000,
      "createdAt": "2024-01-15T10:30:00.000Z"
    }
  ]
}

2. Get Single Customer

GET /customers/:id

Response: 200 OK

{
  "success": true,
  "data": {
    "_id": "507f1f77bcf86cd799439011",
    "name": "Jane Smith",
    "address": "123 Main St, New York, NY",
    "salary": 75000
  }
}

3. Create Customer

POST /customers

Request Body:

{
  "name": "Jane Smith",
  "address": "123 Main St, New York, NY",
  "salary": 75000
}

Response: 201 Created


4. Update Customer

PUT /customers/:id

Request Body:

{
  "name": "Jane Smith Updated",
  "salary": 80000
}

Response: 200 OK


5. Delete Customer

DELETE /customers/:id

Response: 200 OK

{
  "success": true,
  "data": {},
  "message": "Customer deleted successfully"
}
πŸ“¦ Product Endpoints

Note: All product endpoints require authentication.

1. Get All Products

GET /products

Response: 200 OK

{
  "success": true,
  "count": 3,
  "data": [
    {
      "_id": "507f1f77bcf86cd799439012",
      "description": "Laptop Computer",
      "unitPrice": 999.99,
      "qtyOnHand": 50,
      "createdAt": "2024-01-15T10:30:00.000Z"
    }
  ]
}

2. Get Single Product

GET /products/:id


3. Create Product

POST /products

Request Body:

{
  "description": "Gaming Laptop",
  "unitPrice": 1299.99,
  "qtyOnHand": 25
}

Response: 201 Created


4. Update Product

PUT /products/:id

Request Body:

{
  "unitPrice": 1199.99,
  "qtyOnHand": 30
}

5. Delete Product

DELETE /products/:id

πŸ›’ Order Endpoints

Note: All order endpoints require authentication.

1. Get All Orders

GET /orders

Response: 200 OK

{
  "success": true,
  "count": 1,
  "data": [
    {
      "_id": "507f1f77bcf86cd799439013",
      "customer": {
        "_id": "507f1f77bcf86cd799439011",
        "name": "Jane Smith",
        "address": "123 Main St"
      },
      "date": "2024-01-15T10:30:00.000Z",
      "totalAmount": 2599.98,
      "productDetails": [
        {
          "product": {
            "_id": "507f1f77bcf86cd799439012",
            "description": "Gaming Laptop",
            "unitPrice": 1299.99
          },
          "quantity": 2,
          "price": 1299.99
        }
      ]
    }
  ]
}

2. Create Order

POST /orders

Request Body:

{
  "customer": "507f1f77bcf86cd799439011",
  "productDetails": [
    {
      "product": "507f1f77bcf86cd799439012",
      "quantity": 2
    },
    {
      "product": "507f1f77bcf86cd799439013",
      "quantity": 1
    }
  ]
}

Features:

  • βœ… Automatically calculates totalAmount
  • βœ… Validates product availability
  • βœ… Updates inventory (qtyOnHand)
  • βœ… Sets product price at order time

Response: 201 Created


3. Update Order

PUT /orders/:id

Note: Updating an order will:

  1. Restore old product quantities
  2. Validate new product availability
  3. Update inventory with new quantities
  4. Recalculate total amount

4. Delete Order

DELETE /orders/:id

Note: Deleting an order automatically restores product inventory.


πŸ’Ύ Database Schema

πŸ‘€ User Model

{
  name: String,
  email: String (unique),
  password: String (hashed),
  createdAt: Date,
  updatedAt: Date
}

πŸ‘₯ Customer Model

{
  name: String,
  address: String,
  salary: Number,
  createdAt: Date,
  updatedAt: Date
}

πŸ“¦ Product Model

{
  description: String,
  unitPrice: Number,
  qtyOnHand: Number,
  createdAt: Date,
  updatedAt: Date
}

πŸ›’ Order Model

{
  customer: ObjectId (ref: Customer),
  date: Date,
  totalAmount: Number,
  productDetails: [{
    product: ObjectId (ref: Product),
    quantity: Number,
    price: Number
  }],
  createdAt: Date,
  updatedAt: Date
}

πŸ“ Project Structure

express-mongo-mvc/
β”‚
β”œβ”€β”€ πŸ“‚ config/
β”‚   └── db.js                    # Database connection
β”‚
β”œβ”€β”€ πŸ“‚ models/
β”‚   β”œβ”€β”€ User.js                  # User schema & methods
β”‚   β”œβ”€β”€ Customer.js              # Customer schema
β”‚   β”œβ”€β”€ Product.js               # Product schema
β”‚   └── Order.js                 # Order schema
β”‚
β”œβ”€β”€ πŸ“‚ controllers/
β”‚   β”œβ”€β”€ authController.js        # Authentication logic
β”‚   β”œβ”€β”€ customerController.js    # Customer CRUD logic
β”‚   β”œβ”€β”€ productController.js     # Product CRUD logic
β”‚   └── orderController.js       # Order CRUD logic
β”‚
β”œβ”€β”€ πŸ“‚ routes/
β”‚   β”œβ”€β”€ authRoutes.js           # Auth endpoints
β”‚   β”œβ”€β”€ customerRoutes.js       # Customer endpoints
β”‚   β”œβ”€β”€ productRoutes.js        # Product endpoints
β”‚   └── orderRoutes.js          # Order endpoints
β”‚
β”œβ”€β”€ πŸ“‚ middleware/
β”‚   └── auth.js                 # JWT verification
β”‚
β”œβ”€β”€ πŸ“„ server.js                # Application entry point
β”œβ”€β”€ πŸ“„ package.json             # Dependencies
β”œβ”€β”€ πŸ“„ .env                     # Environment variables
β”œβ”€β”€ πŸ“„ .gitignore              # Git ignore rules
└── πŸ“„ README.md               # Documentation

πŸ› οΈ Technologies

Technology Description
Node.js JavaScript Runtime
Express Web Framework
MongoDB NoSQL Database
Mongoose ODM Library
JWT Authentication
bcrypt Password Hashing

Dependencies

{
  "express": "^4.18.2",
  "mongoose": "^8.0.3",
  "bcryptjs": "^2.4.3",
  "jsonwebtoken": "^9.0.2",
  "dotenv": "^16.3.1",
  "cors": "^2.8.5",
  "express-validator": "^7.0.1"
}

πŸ” Testing

Using Postman

  1. Import Collection: Import the API endpoints into Postman
  2. Signup/Login: Get your JWT token
  3. Set Authorization: Add token to Authorization header as Bearer YOUR_TOKEN
  4. Test Endpoints: Try all CRUD operations

Using cURL

# Signup
curl -X POST http://localhost:5000/api/auth/signup \
  -H "Content-Type: application/json" \
  -d '{"name":"John Doe","email":"john@example.com","password":"password123"}'

# Login
curl -X POST http://localhost:5000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"john@example.com","password":"password123"}'

# Get Customers (with token)
curl -X GET http://localhost:5000/api/customers \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

🎯 Best Practices Implemented

βœ… MVC Architecture - Separation of concerns
βœ… RESTful API Design - Standard HTTP methods
βœ… Error Handling - Comprehensive error responses
βœ… Data Validation - Input validation on all endpoints
βœ… Security - JWT authentication & password hashing
βœ… Code Organization - Modular and maintainable
βœ… Environment Variables - Configuration management
βœ… CORS Enabled - Cross-origin resource sharing


🚦 Response Status Codes

Code Description
200 βœ… Success
201 βœ… Created
400 ❌ Bad Request
401 ❌ Unauthorized
404 ❌ Not Found
500 ❌ Server Error

🀝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“ License

This project is licensed under the ISC License.


πŸ‘¨β€πŸ’» Author

Your Name

GitHub LinkedIn Email


πŸ™ Acknowledgments

  • Node.js Community
  • Express.js Team
  • MongoDB Team
  • All contributors and supporters

⭐ Star this repo if you find it helpful!

Made with ❀️ and β˜•

About

init

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •