ecommerce-website/routes/addcart.js

45 lines
1.2 KiB
JavaScript

const express = require('express');
const router = express.Router();
router.get('/', function(req, res, next) {
res.setHeader('Content-Type', 'text/html');
// If the product list isn't set in the session,
// create a new list.
let productList = false;
if (!req.session.productList) {
productList = [];
} else {
productList = req.session.productList;
}
// Add new product selected
// Get product information
let id = false;
let name = false;
let price = false;
if (req.query.id && req.query.name && req.query.price) {
id = req.query.id;
name = req.query.name;
price = req.query.price;
} else {
res.redirect("/listprod");
}
// Update quantity if add same item to order again
if (productList.some(p => p.id == id)) {
productList = productList.map(p => (p.id == id ? {...p, quantity: p.quantity + 1} : p));
} else {
productList.push({
"id": id,
"name": name,
"price": price,
"quantity": 1
});
}
req.session.productList = productList;
res.redirect("/showcart");
});
module.exports = router;