- While I've managed to successfully integrate another service, the challenge now lies in implementing the logic for correctly generating cart items. My goal is to increment the quantity of items in the cart by one with each function call, but it seems that approach isn't working as expected.
- When using
Postman
, I consistently receive the ID of the selected data, which is precisely what I need. - How can I create a
totalQty
variable that increases by 1 every time the function is invoked?
I'm currently retrieving information from another service and attempting to integrate it into an existing function called AddProduct()
.
app.get('/add-to-cart/:id', async (req, res) => {
try {
let id = req.params.id;
let cart = new Cart(req.body.cart ? req.body.cart : {});
const { data } = await axios.get('http://localhost:4200/products');
const singleProduct = await data.find((product) => product._id === id)
cart.addProduct(singleProduct, singleProduct._id);
req.body.cart = cart;
res.redirect('/');
console.log(req.body.cart);
}
catch (error){
console.log(error)
}
});
Here's the logic behind adding items to the cart:
module.exports = function Cart(oldCart) {
this.productItems = oldCart.productItems || {};
this.totalQty = oldCart.totalQty || oldCart.totalQty==0.00;
this.totalPrice = oldCart.totalPrice || oldCart.totalPrice==0.00;
this.addProduct = function(item, id) {
let storedItem = this.productItems;
storedItem = this.productItems = {item: item, qty: 0, price: 0};
if (!storedItem){
storedItem = this.productItems = {item: item, qty: 0, price: 0};
console.log("stored is empty")
}
else{
console.log("Stored item full!")
storedItem = this.productItems = {item: item, qty: storedItem.qty, price: storedItem.price}
storedItem.qty++;
storedItem.price = storedItem.item.price * storedItem.qty;
this.totalQty ++;
this.totalPrice += storedItem.price;
}
}
this.generateArray = function () {
let arr = [];
for (let id in this.productItems) {
arr.push(this.productItems);
}
return arr;
}};
These are the results displayed with console.log