v2/examples/05-swarm-apps/rest-api-advanced/README.md
A production-ready REST API built with Node.js, Express, and MongoDB, featuring comprehensive authentication, e-commerce functionality, and enterprise-grade security.
rest-api-advanced/
├── src/
│ ├── config/ # Configuration files
│ │ ├── database.js # MongoDB connection
│ │ ├── redis.js # Redis connection
│ │ └── config.js # App configuration
│ ├── controllers/ # Route controllers
│ │ ├── auth.controller.js
│ │ ├── user.controller.js
│ │ ├── product.controller.js
│ │ └── order.controller.js
│ ├── middleware/ # Custom middleware
│ │ ├── auth.js # Authentication middleware
│ │ ├── errorHandler.js
│ │ ├── validate.js # Validation middleware
│ │ └── upload.js # File upload middleware
│ ├── models/ # Mongoose models
│ │ ├── User.js
│ │ ├── Product.js
│ │ ├── Order.js
│ │ └── Token.js
│ ├── routes/ # API routes
│ │ ├── auth.routes.js
│ │ ├── user.routes.js
│ │ ├── product.routes.js
│ │ ├── order.routes.js
│ │ └── health.routes.js
│ ├── services/ # Business logic
│ │ ├── auth.service.js
│ │ ├── email.service.js
│ │ ├── cache.service.js
│ │ └── payment.service.js
│ ├── utils/ # Utility functions
│ │ ├── logger.js
│ │ ├── ApiError.js
│ │ ├── asyncHandler.js
│ │ └── helpers.js
│ └── validators/ # Request validators
│ ├── auth.validator.js
│ ├── user.validator.js
│ └── product.validator.js
├── tests/ # Test files
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ └── setup.js # Test configuration
├── docs/ # Documentation
├── scripts/ # Utility scripts
├── .env.example # Environment variables example
├── .eslintrc.js # ESLint configuration
├── .gitignore # Git ignore file
├── docker-compose.yml # Docker compose for local development
├── Dockerfile # Docker configuration
├── jest.config.js # Jest configuration
├── package.json # NPM dependencies
├── README.md # Project documentation
└── server.js # Application entry point
# Clone the repository
git clone <repository-url>
cd rest-api-advanced
# Run the quick start script
./scripts/quick-start.sh
This script will:
git clone <repository-url>
cd rest-api-advanced
npm install
cp .env.example .env
# Edit .env with your configuration
docker-compose up -d mongodb redis
Or install MongoDB and Redis locally.
.env file with required variables:# Server
PORT=3000
NODE_ENV=development
# Database
MONGODB_URI=mongodb://localhost:27017/rest-api-advanced
# JWT
JWT_SECRET=your-super-secret-jwt-key-min-32-chars
JWT_EXPIRE=7d
# Redis (optional)
REDIS_HOST=localhost
REDIS_PORT=6379
npm run seed
This creates:
[email protected] / password123[email protected] / password123npm run dev
The API will be available at http://localhost:3000
docker-compose up --build
This will start:
http://localhost:3000/apihttp://localhost:3000/api-docshttp://localhost:3000/api/healthOnce the server is running, you can access:
http://localhost:3000/api-docs/docs/postman-collection.json/docs/API.mdhttp://localhost:3000/api/healthhttp://localhost:3000/apiPOST /api/auth/register - Register a new userPOST /api/auth/login - Login userPOST /api/auth/logout - Logout userPOST /api/auth/refresh - Refresh access tokenPOST /api/auth/forgot-password - Request password resetPOST /api/auth/reset-password - Reset passwordGET /api/auth/verify-email/:token - Verify email addressPOST /api/auth/resend-verification - Resend verification emailGET /api/auth/me - Get current userPOST /api/auth/check-password - Check password strengthGET /api/users - Get all users (admin only)GET /api/users/profile - Get current user profileGET /api/users/:id - Get user by ID (admin only)PUT /api/users/profile - Update current user profilePUT /api/users/:id - Update user (admin only)DELETE /api/users/:id - Delete user (admin only)POST /api/users/avatar - Upload user avatarPUT /api/users/change-password - Change passwordGET /api/products - Get all products (with pagination, filtering, sorting)GET /api/products/:id - Get product by IDPOST /api/products - Create product (admin only)PUT /api/products/:id - Update product (admin only)DELETE /api/products/:id - Delete product (admin only)POST /api/products/:id/images - Upload product images (admin only)DELETE /api/products/:id/images/:imageId - Delete product image (admin only)GET /api/products/category/:category - Get products by categoryGET /api/products/featured - Get featured productsGET /api/products/popular - Get popular productsGET /api/products/:id/related - Get related productsPOST /api/products/:id/reviews - Add product reviewPUT /api/products/:id/reviews - Update product reviewDELETE /api/products/:id/reviews - Delete product reviewPOST /api/products/:id/reviews/:reviewId/helpful - Mark review as helpfulPUT /api/products/:id/inventory - Update inventory (admin only)PUT /api/products/inventory/bulk - Bulk update inventory (admin only)GET /api/products/inventory/report - Get inventory report (admin only)GET /api/products/categories/list - Get all categoriesGET /api/products/export/data - Export products (admin only)GET /api/orders - Get user ordersGET /api/orders/:id - Get order by IDPOST /api/orders - Create orderDELETE /api/orders/:id - Cancel orderGET /api/orders/admin/all - Get all orders (admin only)PUT /api/orders/:id/status - Update order status (admin only)POST /api/orders/:id/tracking - Add tracking info (admin only)POST /api/orders/:id/refund - Process refund (admin only)POST /api/orders/:id/note - Add internal note (admin only)GET /api/orders/statistics/summary - Get order statisticsGET /api/orders/reports/sales - Get sales report (admin only)GET /api/orders/:id/invoice - Get order invoiceGET /api/orders/export/data - Export orders (admin only)GET /api/health - Basic health checkGET /api/health/ready - Readiness checkGET /api/health/live - Liveness checkThe API uses JWT (JSON Web Tokens) for authentication. Include the token in the Authorization header:
Authorization: Bearer <your-jwt-token>
/api/auth/refresh endpoint to get new access token{
"data": {
"field1": "value1",
"field2": "value2"
}
}
{
"success": true,
"data": {
"id": "123",
"field1": "value1",
"field2": "value2"
},
"message": "Operation successful"
}
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Validation failed",
"details": [
{
"field": "email",
"message": "Invalid email format"
}
]
},
"requestId": "550e8400-e29b-41d4-a716-446655440000"
}
{
"success": true,
"data": [...],
"pagination": {
"page": 1,
"limit": 20,
"total": 100,
"pages": 5,
"hasNext": true,
"hasPrev": false
}
}
The project includes comprehensive test suites for both unit and integration testing.
npm test
npm run test:unit
npm run test:integration
npm run test:coverage
Unit Tests: Located in /tests/unit/
Integration Tests: Located in /tests/integration/
The project uses ESLint with Airbnb base configuration. Run linting:
npm run lint
npm run lint:fix
Key environment variables (see .env.example for complete list):
# Server Configuration
PORT=3000
NODE_ENV=development
API_URL=http://localhost:3000
# Database
MONGODB_URI=mongodb://localhost:27017/rest-api-advanced
# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
# JWT
JWT_SECRET=your-super-secret-jwt-key-min-32-chars
JWT_EXPIRE=7d
JWT_REFRESH_EXPIRE=30d
ROTATE_REFRESH_TOKENS=true
# Security
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001
BCRYPT_ROUNDS=10
# Rate Limiting
RATE_LIMIT_WINDOW=15
RATE_LIMIT_MAX=100
AUTH_RATE_LIMIT_MAX=5
# Seed all data (users, products, orders)
npm run seed
# Seed specific data
npm run seed:products
npm run seed:orders
# Clean and reseed database
npm run seed:clean
Default seed accounts:
[email protected] / password123[email protected] / password123NODE_ENV=productiondocker build -t rest-api-advanced .
docker run -p 3000:3000 --env-file .env rest-api-advanced
pm2 start ecosystem.config.js --env production
git checkout -b feature/amazing-feature)git commit -m 'Add some amazing feature')git push origin feature/amazing-feature)This project is licensed under the MIT License - see the LICENSE file for details.
For support, email [email protected] or create an issue in the repository.