A comprehensive Express.js API featuring e-commerce functionality, document management, JWT authentication, and MongoDB integration. This project demonstrates modern Node.js development practices with extensive testing coverage.
- JWT-based authentication with bcrypt password hashing
- Role-based access control (user/admin)
- Secure middleware protection for private routes
- Input validation and sanitization
- Product catalog management (CRUD operations)
- Shopping cart functionality with automatic calculations
- User-specific cart management
- Admin-only product management
- Secure file upload (images and audio, max 10MB)
- File integrity validation with hash verification
- Multer-based file handling with filtering
- Document metadata storage and retrieval
- 100+ comprehensive tests with 90%+ coverage
- Unit and integration test separation
- Professional test helpers and utilities
- Legacy test compatibility
- Node.js 14+ installed
- MongoDB Atlas account or local MongoDB
- Environment variables configured
# Clone the repository
git clone https://github.com/Biohazardyee/JScript-Full-Stack-Project.git
cd JScript-Full-Stack-Project/App
# Install dependencies
npm install
# Configure environment (see Environment Setup below)
cp .env.example .env
# Start development server
npm run devServer: http://localhost:3000
JScript-Full-Stack-Project/
βββ .gitignore # Git ignore patterns
βββ README.md # Main project documentation
βββ App/ # Main application directory
βββ .env # Environment variables (not in git)
βββ .mocharc.json # Mocha test configuration
βββ .nycrc # Coverage configuration
βββ app.js # Express application entry point
βββ package.json # Dependencies and scripts
βββ package-lock.json # Dependency lock file
β
βββ bin/ # Server startup scripts
β βββ www # Server bootstrap
β
βββ config/ # Configuration files
β βββ database.js # Database connection setup
β
βββ data/ # Data storage (JSON files)
β βββ cart.json # Shopping cart data
β βββ documents.json # Document metadata
β βββ products.json # Product catalog
β βββ uploads/ # Uploaded file storage
β
βββ imgs/ # Test images for development
β
βββ middleware/ # Custom middleware
β βββ auth.js # Authentication middleware
β
βββ public/ # Static assets
β βββ images/
β βββ javascripts/
β βββ stylesheets/
β βββ style.css
β
βββ routes/ # API route definitions
β βββ articles.js # Product CRUD operations
β βββ cart.js # Shopping cart management
β βββ documents.js # File upload/download
β βββ login.js # User authentication
β βββ register.js # User registration
β
βββ schemas/ # Validation schemas
β βββ validation.js # Input validation rules
β
βββ test/ # Test suite
β βββ setup.js # Test environment setup
β βββ README.md # Testing documentation
β βββ helpers/ # Shared test utilities
β βββ unit/ # Unit tests
β βββ integration/ # Integration tests
β βββ legacy/ # Original working tests
β
βββ utilities/ # Helper functions
β βββ utilities.js # File I/O and utility functions
β
βββ views/ # EJS templates
βββ error.ejs # Error page template
βββ index.ejs # Home page template
Create a .env file in the /App directory:
# JWT Configuration
JWT_SECRET=your_super_secure_jwt_secret_here
# MongoDB Configuration
MongoDBConnection=mongodb+srv://username:password@cluster0.xxxxx.mongodb.net/ecommerce
# Environment
NODE_ENV=development
# Optional: Port configuration
PORT=3000MongoDB Atlas Setup:
- Create a free MongoDB Atlas account at mongodb.com/atlas
- Create a new cluster (M0 tier is free)
- Create a database user with read/write permissions
- Get your connection string from "Connect" β "Connect your application"
- Replace
<username>,<password>, and<databasename>in your connection string - Add the connection string to your
.envfile
This API uses JWT (JSON Web Tokens) for authentication with bcrypt password hashing.
| Password | Roles | |
|---|---|---|
admin@example.com |
password123 |
admin, user |
user@example.com |
password123 |
user |
POST /register
Headers:
Content-Type: application/json
Body:
{
"email": "newuser@example.com",
"password": "securepassword123"
}Success Response:
{
"success": true,
"message": "Added user",
"data": "User nΒ°507f1f77bcf86cd799439011, email: newuser@example.com with roles: user was created"
}Validation Requirements:
- Email must be unique and valid format
- Password must be at least 8 characters long
- Both fields are required
POST /register with user details (see User Registration section above)
POST /login
Headers:
Content-Type: application/json
Body:
{
"email": "admin@example.com",
"password": "password123"
}Success Response:
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "507f1f77bcf86cd799439011",
"email": "admin@example.com",
"roles": ["admin", "user"]
}
}Headers for all protected routes:
Authorization: Bearer YOUR_JWT_TOKEN_HERE
Content-Type: application/json
| Method | URL | Body | Description | Required Role |
|---|---|---|---|---|
| GET | /articles |
- | Get all products | user |
| GET | /articles/:id |
- | Get single product | user |
| POST | /articles |
{"name": "Product", "price": 99.99} |
Create product | admin |
| PUT | /articles/:id |
{"name": "Updated", "price": 129.99} |
Update product | admin |
| DELETE | /articles/:id |
- | Delete product | admin |
| DELETE | /articles |
- | Delete all products | admin |
| Method | URL | Body | Description | Required Role |
|---|---|---|---|---|
| GET | /cart |
- | View cart with balance | user |
| POST | /cart |
{"productId": 1, "quantity": 2} |
Add to cart | user |
| PUT | /cart/:id |
{"quantity": 5} |
Update cart item | user |
| DELETE | /cart/:id |
- | Remove cart item | user |
| DELETE | /cart |
- | Clear cart | user |
-
Register a New User (Optional)
- POST
/register - Headers:
Content-Type: application/json - Body:
{"email": "testuser@example.com", "password": "password123"}
- POST
-
Login as Admin (or your new user)
- POST
/loginwith admin credentials or your new user - Copy the JWT token from response
- POST
-
Create a Product (Admin only)
- POST
/articles - Headers:
Authorization: Bearer YOUR_TOKEN,Content-Type: application/json - Body:
{"name": "Test Product", "price": 29.99}
- POST
-
View All Products
- GET
/articles - Headers:
Authorization: Bearer YOUR_TOKEN
- GET
-
Add Product to Cart
- POST
/cart - Headers:
Authorization: Bearer YOUR_TOKEN,Content-Type: application/json - Body:
{"productId": 1, "quantity": 2}
- POST
-
View Cart with Balance
- GET
/cart - Headers:
Authorization: Bearer YOUR_TOKEN
- GET
- No token: Access any protected route without Authorization header
- Invalid token: Use malformed or expired token
- Wrong format: Use token without "Bearer " prefix
- Wrong credentials: Login with incorrect email/password
| Status | Error | Cause |
|---|---|---|
| 401 | Authorization header missing or malformed |
Missing token or wrong format |
| 401 | Invalid email or password |
Wrong login credentials |
| 403 | Invalid password or email credentials |
Password doesn't match |
| 403 | Insufficient privileges |
User role can't access admin endpoints |
| 404 | Product/item not found | Invalid ID in URL |
| 500 | Server error | Internal server error |
- Database: MongoDB Atlas cloud database with Mongoose ODM
- Environment Variables: JWT secret and MongoDB connection string stored in
.envfile - Password Security: Bcrypt with salt rounds = 10
- Token Format: Bearer token in Authorization header
- Route Protection: Middleware applied after login/register routes
- User Storage: MongoDB Atlas with mongoose schema validation
- Schema Validation:
- Email: required, unique, lowercase, valid format
- Password: required, minimum 8 characters, bcrypt hashed
- Roles: array with default value ['user']
- Timestamps: automatic createdAt/updatedAt fields
- Database Connection: Automatic connection on app startup with success/error logging
- Organized Structure: Separate unit, integration, and legacy test directories
- Shared Helpers: Centralized test utilities and helper classes
- Legacy Compatibility: Preserved working tests during refactoring
- Documentation: Comprehensive test documentation in
/test/README.md
- Statements: 100% (60/60)
- Functions: 100% (18/18)
- Lines: 100% (52/52)
- Branches: 93.93% (31/33)
# Run main test suite
npm test
# Run specific test types
npm run test:unit # Unit tests only
npm run test:integration # Integration tests only
npm run test:legacy # Original working tests
# Development workflow
npm run test:watch # Watch mode for development
npm run test:coverage # Generate coverage report
# Test with real file operations
npm run test:legacy:image # Real image upload/download test- Utilities: File I/O operations (readJson, writeJson, readCart, readProducts)
- Middleware: Authentication and authorization middleware
- Helpers: ID generation, product validation, cart calculations
- Integration: Complex functions combining multiple dependencies
- Mocking: File system operations and HTTP middleware
- Edge Cases: Null inputs, empty arrays, invalid data
- Error Handling: File errors, JSON parsing errors, exceptions
- Spying: Function call verification and argument checking
Coverage reports available in ./coverage/index.html after running tests.