CART API
Mon Mar 13 2023 10:46:50 GMT+0000 (Coordinated Universal Time)
Saved by @SandeepBalli
// Importing necessary packages
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
// Creating express app
const app = express();
// Using body-parser to parse incoming JSON requests
app.use(bodyParser.json());
// Connecting to MongoDB using mongoose
mongoose.connect('mongodb://localhost/shopping_cart', {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log('Database connected successfully');
}).catch((error) => {
console.log('Error connecting to database', error);
});
// Defining product schema
const productSchema = new mongoose.Schema({
name: String,
description: String,
price: Number,
imageUrl: String,
});
// Defining cart schema
const cartSchema = new mongoose.Schema({
products: [{
product: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
},
quantity: {
type: Number,
default: 1,
},
}],
totalPrice: {
type: Number,
default: 0,
},
});
// Creating models for product and cart
const Product = mongoose.model('Product', productSchema);
const Cart = mongoose.model('Cart', cartSchema);
// Creating endpoint for creating a new product
app.post('/api/products', async (req, res) => {
const product = new Product({
name: req.body.name,
description: req.body.description,
price: req.body.price,
imageUrl: req.body.imageUrl,
});
await product.save();
res.json(product);
});
// Creating endpoint for getting all products
app.get('/api/products', async (req, res) => {
const products = await Product.find();
res.json(products);
});
// Creating endpoint for getting a single product by ID
app.get('/api/products/:id', async (req, res) => {
const product = await Product.findById(req.params.id);
res.json(product);
});
// Creating endpoint for adding a product to the cart
app.post('/api/cart/:productId', async (req, res) => {
// Find the product by ID in the database
const product = await Product.findById(req.params.productId);
if (!product) {
return res.status(404).json({ message: 'Product not found' });
}
// Find the cart in the database or create a new one if none exists
let cart = await Cart.findOne();
if (!cart) {
cart = new Cart();
}
// Check if the product is already in the cart
const existingProduct = cart.products.find(p => p.product.toString() === product._id.toString());
if (existingProduct) {
// If the product is already in the cart, increase the quantity
existingProduct.quantity++;
} else {
// If the product is not in the cart, add it with a quantity of 1
cart.products.push({ product: product._id });
}
// Add the product price to the cart's total price and save the cart to the database
cart.totalPrice += product.price;
await cart.save();
// Return the updated cart
res.json(cart);
});
// Creating endpoint for getting the cart
app.get('/api/cart', async (req, res) => {
// Find the cart in the database and populate the products array with the corresponding products
const cart = await Cart.findOne().populate('products.product');
res.json(cart);
});
// Creating endpoint for removing a product from the cart
app.delete('/api/cart/:productId', async (req, res) => {
// Find the cart in the database
const cart = await Cart.findOne();
if (!cart) {
return res.status(404).json({ message: 'Cart not found' });
}
// Find the product in the cart
const product = cart.products.find(p => p.product.toString() === req.params.productId.toString());
if (!product) {
return res.status(404).json({ message: 'Product not found in cart' });
}
// If the quantity of the product is greater than 1, decrease the quantity by 1
if (product.quantity > 1) {
product.quantity--;
} else {
// If the quantity of the product is 1, remove it from the cart
cart.products = cart.products.filter(p => p.product.toString() !== req.params.productId.toString());
}
// Subtract the product price from the cart's total price and save the cart to the database
const removedProduct = await Product.findById(req.params.productId);
cart.totalPrice -= removedProduct.price;
await cart.save();
// Return the updated cart
res.json(cart);
});
// Creating endpoint for deleting all products from the cart
app.delete('/api/cart', async (req, res) => {
// Find the cart in the database
const cart = await Cart.findOne();
if (!cart) {
return res.status(404).json({ message: 'Cart not found' });
}
// Clear the products array and set the total price to 0
cart.products = [];
cart.totalPrice = 0;
await cart.save();
// Return the empty cart
res.json(cart);
});
// Starting the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(Server started on port ${port});
});
// Exporting the app for testing
module.exports = app;



Comments