Back to Tutorials

Building a Complete Cloud Application: E-Commerce API

Project Overview

We'll build a complete e-commerce API with products, cart, and orders. This demonstrates how to structure a real-world cloud application.

Database Schema

// Product Schema
const productSchema = new mongoose.Schema({
  name: String,
  price: Number,
  description: String,
  stock: Number,
  category: String
});

// Order Schema
const orderSchema = new mongoose.Schema({
  userId: mongoose.Schema.Types.ObjectId,
  items: [{
    productId: mongoose.Schema.Types.ObjectId,
    quantity: Number,
    price: Number
  }],
  total: Number,
  status: { type: String, default: 'pending' },
  createdAt: { type: Date, default: Date.now }
});

API Endpoints

// Products
GET    /api/products           // List all products
GET    /api/products/:id       // Get product details
POST   /api/products           // Create product (admin)
PUT    /api/products/:id       // Update product (admin)
DELETE /api/products/:id       // Delete product (admin)

// Cart
GET    /api/cart               // Get user cart
POST   /api/cart/items         // Add item to cart
PUT    /api/cart/items/:id     // Update cart item
DELETE /api/cart/items/:id     // Remove from cart

// Orders
GET    /api/orders             // Get user orders
POST   /api/orders             // Create order
GET    /api/orders/:id         // Get order details

Implementation Example

// Cart management
app.post('/api/cart/items', authenticateToken, async (req, res) => {
  try {
    const { productId, quantity } = req.body;
    const product = await Product.findById(productId);
    if (!product) {
      return res.status(404).json({ error: 'Product not found' });
    }
    // Add to user's cart (stored in database or session)
    // Implementation depends on your cart storage strategy
    res.json({ message: 'Item added to cart' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Create order
app.post('/api/orders', authenticateToken, async (req, res) => {
  try {
    const cart = await getCart(req.user.userId);
    const order = new Order({
      userId: req.user.userId,
      items: cart.items,
      total: cart.total
    });
    await order.save();
    await clearCart(req.user.userId);
    res.status(201).json(order);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

Deployment Checklist

  • Set up cloud database (MongoDB Atlas, AWS RDS)
  • Configure environment variables
  • Set up CI/CD pipeline
  • Configure domain and SSL
  • Set up monitoring and logging
  • Implement backup strategy

Scaling Considerations

  • Use load balancers for multiple servers
  • Implement caching (Redis)
  • Use CDN for static assets
  • Database replication for high availability
  • Microservices architecture for large apps