Skip to content

mjalav/my-basket-app

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

100 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

MyBasket Lite - Microservices Retail Application

πŸŽ‰ This is a fork of uppadhyayraj/my-basket-app with Windows compatibility improvements!

A modern, scalable retail application built with Next.js frontend and Node.js microservices architecture. This application has been transformed from a monolithic structure into a distributed microservices system.

✨ Fork Enhancements

This fork adds:

  • πŸͺŸ Windows Command Prompt compatibility - All scripts work natively on Windows
  • 🎨 UTF-8 emoji support - Proper emoji display in Windows terminals
  • πŸ“š Enhanced documentation - Complete setup instructions for both platforms
  • πŸ”„ Cross-platform npm scripts - OS-specific variants for seamless development
  • πŸ₯ Production-grade health monitoring - Advanced liveness/readiness probes and resource monitoring
  • πŸ§ͺ Automated API Testing - Comprehensive Playwright test suite for service reliability

πŸ—οΈ Architecture Overview

The application consists of the following microservices:

Frontend

  • Next.js Application (Port 9002) - React-based frontend with server-side rendering

Microservices

  • API Gateway (Port 3000) - Central entry point, routing, rate limiting, and load balancing
  • Product Service (Port 3001) - Product catalog management
  • Cart Service (Port 3002) - Shopping cart operations (includes advanced health monitoring)
  • Order Service (Port 3003) - Order processing and management
  • AI Service (Port 3004) - AI-powered recommendations and suggestions

πŸš€ Quick Start

Option 1: Development Mode (Recommended for development)

  1. Install dependencies for all services:

    npm install
    npm run microservices:install
  2. Start all microservices:

    npm run microservices:start
  3. Start the frontend (in a new terminal):

    npm run dev
  4. Verify everything is running:

    npm run microservices:health

The application will be available at:

Option 2: Docker (Recommended for production-like testing)

  1. Build and start all services:

    npm run docker:build
    npm run docker:up
  2. View logs:

    npm run docker:logs
  3. Stop all services:

    npm run docker:down

πŸ“‹ Available Scripts

Development Scripts

  • npm run dev - Start Next.js frontend in development mode
  • npm run dev:full - Start microservices and frontend together
  • npm run build - Build the Next.js application
  • npm run start - Start the Next.js application in production mode

Microservices Scripts

  • npm run microservices:install - Install dependencies for all microservices
  • npm run microservices:start - Start all microservices in development mode
  • npm run microservices:stop - Stop all running microservices
  • npm run microservices:health - Check health of all microservices

Windows Compatibility

For Windows users, OS-specific scripts are available:

  • npm run microservices:start:win - Start microservices using Windows batch files
  • npm run microservices:stop:win - Stop microservices using Windows batch files
  • npm run microservices:health:win - Health check using Windows batch files

Note: Windows batch files include UTF-8 encoding (chcp 65001) for proper emoji display in Command Prompt.

Docker Scripts

  • npm run docker:build - Build all Docker images
  • npm run docker:up - Start all services with Docker Compose
  • npm run docker:down - Stop and remove all Docker containers
  • npm run docker:logs - View logs from all services

Testing Scripts

  • npm run lint - Run ESLint
  • npm run typecheck - Run TypeScript type checking
  • npm run test:api - Run comprehensive Playwright API tests
  • npm run test:report - Generate HTML test reports for API tests

πŸ“š Assignments

πŸ”§ Service Details

API Gateway (Port 3000)

Endpoints:

  • GET /health - Overall system health check
  • GET /info - Gateway and service information
  • /api/products/* - Proxy to Product Service
  • /api/cart/* - Proxy to Cart Service
  • /api/orders/* - Proxy to Order Service
  • /api/recommendations/* - Proxy to AI Service

Product Service (Port 3001)

Endpoints:

  • GET /api/products - List products with filtering and pagination
  • GET /api/products/:id - Get specific product
  • POST /api/products - Create new product
  • PUT /api/products/:id - Update product
  • DELETE /api/products/:id - Delete product
  • GET /api/categories - Get product categories
  • GET /api/health - Service health check

Query Parameters for GET /api/products:

  • category - Filter by category
  • minPrice - Minimum price filter
  • maxPrice - Maximum price filter
  • inStock - Filter by stock availability
  • search - Search in name/description
  • page - Page number (default: 1)
  • limit - Items per page (default: 10, max: 100)

Cart Service (Port 3002)

Endpoints:

  • GET /api/cart/:userId - Get user's cart
  • POST /api/cart/:userId/items - Add item to cart
  • PUT /api/cart/:userId/items/:productId - Update cart item quantity
  • DELETE /api/cart/:userId/items/:productId - Remove item from cart
  • DELETE /api/cart/:userId - Clear entire cart
  • GET /api/cart/:userId/summary - Get cart summary
  • GET /api/health - Comprehensive service health check (diagnostics)
  • GET /api/health/live - Liveness probe (process check)
  • GET /api/health/ready - Readiness probe (dependency and resource check)

Order Service (Port 3003)

Endpoints:

  • POST /api/orders/:userId - Create new order
  • GET /api/orders/:userId - Get user's orders
  • GET /api/orders/:userId/:orderId - Get specific order
  • PUT /api/orders/:userId/:orderId/status - Update order status
  • POST /api/orders/:userId/:orderId/cancel - Cancel order
  • GET /api/health - Service health check

AI Service (Port 3004)

Endpoints:

  • POST /api/recommendations/grocery-suggestions - Get grocery suggestions
  • POST /api/recommendations/personalized - Get personalized recommendations
  • POST /api/grocery-suggestions - Legacy endpoint
  • GET /api/health - Service health check

πŸ§ͺ Testing the Application

Manual Testing

  1. Start the services:

    npm run microservices:start
    npm run dev
  2. Test Product Service:

    curl http://localhost:3001/api/products
    curl http://localhost:3001/api/products/1
    curl http://localhost:3001/api/categories
  3. Test Cart Service:

    # Add item to cart
    curl -X POST http://localhost:3002/api/cart/user-123/items \
      -H "Content-Type: application/json" \
      -d '{"productId": "1", "quantity": 2}'
    
    # Get cart
    curl http://localhost:3002/api/cart/user-123
  4. Test AI Service:

    curl -X POST http://localhost:3004/api/recommendations/grocery-suggestions \
      -H "Content-Type: application/json" \
      -d '{"cartItems": ["apples", "chicken"]}'
  5. Test through API Gateway:

    curl http://localhost:3000/api/products
    curl http://localhost:3000/health

Frontend Testing

  1. Visit http://localhost:9002
  2. Browse products
  3. Add items to cart
  4. View cart and checkout
  5. Check order history

Automated API Testing

The application includes a professional API testing framework built with Playwright and TypeScript covering all microservices.

  1. Navigate to the test directory:

    cd my-basket-api-tests
  2. Run the full test suite:

    npm install
    npm test
  3. Run tests for specific issues:

    # Test dependency validation
    npm test -- tests/cart-service/health-audit/issue1-dependency.spec.ts
  4. View test reports:

    npx playwright show-report
  5. Run challenge or specific tests:

    # Run only the Challenge 1.3.4 order-service tests
    npx playwright test tests/order-service/order.spec.ts -g "1.3.4Challenge" --workers=1
    
    # Run a single test by title (example)
    npx playwright test -g "1.3.4Challenge - rounding to cents succeeds"

⚠️ Important: Rate Limiting & Test Configuration

Rate Limiting in Development:

  • The API Gateway's rate limiter is set to 1,000,000 requests/15 minutes for development
  • This is configured in microservices/api-gateway/src/index.ts
  • Production uses strict 1,000 requests/15 minutes limit
  • 🚨 If rate limit is reduced in development: Tests will fail with HTTP 429 (Too Many Requests) errors

Test Execution:

  • Test suite runs with sequential execution (1 worker) to avoid state conflicts
  • This is configured in my-basket-api-tests/playwright.config.ts
  • 🚨 If changed to parallel execution: Tests may fail due to shared microservice state interference
  • Sequential execution takes ~35 seconds; parallel would be ~16-20 seconds but with intermittent failures

Why These Settings Matter:

  • Parallel test workers against shared microservice instances cause state conflicts (carts, orders, products interfering between tests)
  • Low rate limits cause HTTP 429 rejections when multiple tests hit the gateway simultaneously
  • These are development-only optimizations; production deployments maintain strict security limits

For CI/CD Pipelines:

# Override to parallel if services are isolated per worker
WORKERS=6 npm test

# Or keep sequential for stable results
npm test  # Uses workers: 1 by default

πŸ”’ Environment Variables

Frontend (.env.local)

NEXT_PUBLIC_API_URL=http://localhost:3000

Microservices (.env files in each service)

# Common
NODE_ENV=development
PORT=300X

# Service-specific
PRODUCT_SERVICE_URL=http://localhost:3001
CART_SERVICE_URL=http://localhost:3002
ORDER_SERVICE_URL=http://localhost:3003
AI_SERVICE_URL=http://localhost:3004

πŸ“ Project Structure

β”œβ”€β”€ src/                          # Next.js frontend source
β”‚   β”œβ”€β”€ app/                      # App router pages
β”‚   β”œβ”€β”€ components/               # React components
β”‚   β”œβ”€β”€ contexts/                 # React contexts
β”‚   β”œβ”€β”€ lib/                      # Utilities and API clients
β”‚   β”‚   └── api/                  # Microservice API clients
β”‚   └── data/                     # Sample data (fallback)
β”œβ”€β”€ microservices/                # Microservices directory
β”‚   β”œβ”€β”€ api-gateway/              # API Gateway service
β”‚   β”œβ”€β”€ product-service/          # Product management service
β”‚   β”œβ”€β”€ cart-service/             # Shopping cart service
β”‚   β”œβ”€β”€ order-service/            # Order management service
β”‚   └── ai-service/               # AI recommendations service
β”œβ”€β”€ cart-service-api-tests/        # Playwright API test suite for Cart Service
β”œβ”€β”€ Assignments/                  # Audit trail of AI prompts and reports
β”œβ”€β”€ scripts/                      # Development scripts
β”œβ”€β”€ docker-compose.yml            # Docker configuration
└── README.md                     # This file

πŸ› Troubleshooting

Services Won't Start

  1. Check if ports are available: npm run microservices:stop
  2. Install dependencies: npm run microservices:install
  3. Check Node.js version (requires Node 18+)

Frontend Can't Connect to Services

  1. Verify microservices are running: npm run microservices:health
  2. Check API Gateway is accessible: curl http://localhost:3000/health
  3. Verify environment variables in .env.local

Docker Issues

  1. Ensure Docker is running
  2. Clean up: docker system prune -f
  3. Rebuild: npm run docker:build

API Tests Failing with HTTP 429 (Too Many Requests)

Problem: Tests fail with "Too many requests from this IP" errors

  • Check rate limit in microservices/api-gateway/src/index.ts
  • Ensure it's set to 1000000 (1 million) for development, NOT 50000

Solution:

  1. Restart API Gateway to apply rate limit changes:

    cd microservices/api-gateway
    npm run build
    docker-compose down api-gateway
    docker-compose up -d api-gateway
  2. Verify rate limit is applied:

    npm run microservices:health

API Tests Failing with Intermittent Failures (state conflicts)

Problem: Tests pass sometimes, fail other times

  • Check test worker configuration in my-basket-api-tests/playwright.config.ts
  • Ensure workers: 1 is set (sequential execution)

Solution:

  1. Verify sequential execution:

    grep "workers:" my-basket-api-tests/playwright.config.ts

    Should show: workers: 1,

  2. Run test suite:

    cd my-basket-api-tests
    npm test  # Sequential execution (stable, ~35s)
  3. If you need parallel testing, ensure service isolation per worker (advanced setup)

πŸš€ Deployment

Production Deployment

  1. Build all services:

    npm run docker:build
  2. Deploy with Docker Compose:

    npm run docker:up
  3. For cloud deployment, consider:

    • Container orchestration (Kubernetes, ECS)
    • Service mesh (Istio, Linkerd)
    • API Gateway (Kong, Ambassador)
    • Monitoring (Prometheus, Grafana)

πŸ› οΈ Development

Adding New Features

  1. Frontend: Add components in src/components/
  2. API: Update service clients in src/lib/api/
  3. Backend: Modify appropriate microservice
  4. Database: Each service manages its own data

Code Style

  • TypeScript for type safety
  • ESLint for code quality
  • Prettier for formatting (configure as needed)

πŸ“ˆ Scaling Considerations

  • Each microservice can be scaled independently
  • Use container orchestration for production
  • Implement caching (Redis) for frequently accessed data
  • Add monitoring and logging
  • Consider message queues for async communication

🀝 Contributing & Forking

How This Repository Was Forked

This repository is a proper fork of uppadhyayraj/my-basket-app with Windows compatibility improvements.

βœ… This is now a proper GitHub fork with full fork relationship established.

Forking Process:

Step 1: Create Your Fork

  1. Go to https://github.com/uppadhyayraj/my-basket-app
  2. Click the "Fork" button (top right)
  3. Select your GitHub account to fork it to

Step 2: Clone Your Repository

# Replace 'mjalav' with your actual GitHub username
git clone https://github.com/mjalav/my-basket-app
cd my-basket-app

⚠️ Important: Replace mjalav with your actual GitHub username before running the command!

Step 3: Add Upstream Remote (for getting updates from original)

git remote add upstream https://github.com/uppadhyayraj/my-basket-app

Step 4: Update from Upstream (when needed)

git fetch upstream
git merge upstream/main

Windows Compatibility Improvements

This fork includes Windows-specific enhancements:

Files Added:

  • scripts/start-microservices.bat - Windows batch script for starting services
  • scripts/stop-microservices.bat - Windows batch script for stopping services
  • scripts/health-check.bat - Windows batch script for health checks

Key Features:

  • UTF-8 encoding support for proper emoji display (chcp 65001)
  • Windows Command Prompt compatibility
  • OS-specific npm scripts (:win and :unix suffixes)
  • Cross-platform development workflow

Branch Structure:

  • main - Synced with upstream repository
  • fix/windows-microservices-compatibility - Windows compatibility features
  • fix/windows-emoji-display-utf8 - UTF-8 encoding improvements

Contributing to This Fork

  1. Fork this repository to your GitHub account:
  2. Clone your fork:
    # Replace 'your-username' with your actual GitHub username
    git clone https://github.com/your-username/my-basket-app
    cd my-basket-app
  3. Set up remotes for upstream synchronization:
    git remote add upstream https://github.com/mjalav/my-basket-app
    git remote -v  # Verify configuration
  4. Create a feature branch:
    git checkout -b feature/your-feature-name
  5. Make changes and test on your platform
  6. Commit with clear messages
  7. Push to your fork:
    git push origin feature/your-feature-name
  8. Create a Pull Request against this repository

Syncing with Upstream Original

To keep your fork updated with the original repository:

# Add original repository as upstream (first time only)
git remote add original-upstream https://github.com/uppadhyayraj/my-basket-app

# Fetch and merge changes from original
git fetch original-upstream
git checkout main
git merge original-upstream/main

# Push updates to your fork
git push origin main

πŸ“„ License

This project is a fork of uppadhyayraj/my-basket-app with enhancements for Windows compatibility. 6. Push and create a pull request

Contributing to Original Repository

To contribute back to the original repository, submit pull requests to uppadhyayraj/my-basket-app.

πŸ“„ License

This project is for educational purposes. Feel free to use and modify as needed.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • TypeScript 91.0%
  • JavaScript 2.5%
  • HTML 1.7%
  • Shell 1.4%
  • Batchfile 0.9%
  • CSS 0.7%
  • Other 1.8%