const express = require("express"); const bodyParser = require("body-parser"); const app = express(); const PORT = 8080; // Middleware to parse JSON app.use(bodyParser.json()); // In-memory data store for demonstration let cartData = { cart: { accessories: {}, }, }; // CREATE - Add or update cart items app.post("/cart", (req, res) => { const { cart } = req.body; if (!cart) { return res.status(400).json({ error: "Cart data is required" }); } // Merge new cart data with existing cart data cartData = { ...cartData, cart: { ...cartData.cart, ...cart, }, }; res.status(201).json({ message: "Cart updated successfully", cart: cartData, }); }); // READ - Get the entire cart app.get("/cart", (req, res) => { res.json({ message: "Cart retrieved successfully", cart: cartData, }); }); // READ - Get a specific item in the cart app.get("/cart/accessories/:key", (req, res) => { const { key } = req.params; const item = cartData.cart.accessories[key]; if (!item) { return res.status(404).json({ error: `Item with key '${key}' not found` }); } res.json({ message: "Item retrieved successfully", item: { [key]: item }, }); }); // UPDATE - Update a specific item in the cart app.put("/cart/accessories/:key", (req, res) => { const { key } = req.params; const { value } = req.body; if (!value) { return res.status(400).json({ error: "Value is required" }); } if (!cartData.cart.accessories[key]) { return res.status(404).json({ error: `Item with key '${key}' not found` }); } // Update the item cartData.cart.accessories[key] = value; res.json({ message: "Item updated successfully", cart: cartData, }); }); // DELETE - Remove a specific item from the cart app.delete("/cart/accessories/:key", (req, res) => { const { key } = req.params; if (!cartData.cart.accessories[key]) { return res.status(404).json({ error: `Item with key '${key}' not found` }); } // Delete the item delete cartData.cart.accessories[key]; res.json({ message: "Item deleted successfully", cart: cartData, }); }); // Start the server app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });