Created
August 17, 2014 08:56
-
-
Save biggora/3d84528842cabed68d60 to your computer and use it in GitHub Desktop.
Shopping cart for TrinteJS framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Shopping Cart manager | |
* | |
* | |
* Created by init script | |
* App based on TrinteJS MVC framework | |
* TrinteJS homepage http://www.trintejs.com | |
**/ | |
exports.addProductToCart = function addProductToCart() { | |
return function(req, res, next) { | |
var newProduct = req.body.product; | |
if (newProduct) { | |
if (req.session) { | |
if (!req.session.cart) { | |
req.session.cart = { | |
sum_total: 0, | |
products: [] | |
}; | |
} | |
var found = false, products = [], sum_total = 0; | |
req.session.cart.products.forEach(function(product) { | |
if (newProduct.id === product.id) { | |
product.qty = (product.qty + newProduct.qty); | |
products.push(product); | |
found = true; | |
} | |
sum_total = sum_total + (product.qty * product.price); | |
}); | |
if (!found) { | |
products.push(newProduct); | |
sum_total = sum_total + (newProduct.qty * newProduct.price); | |
} | |
req.session.cart.products = products; | |
req.session.cart.sum_total = sum_total; | |
res.locals({ | |
cart: req.session.cart | |
}); | |
res.send('Product added!'); | |
} | |
} else { | |
res.send('Invalid product!'); | |
} | |
}; | |
}; | |
exports.getProductFromCart = function getProductFromCart() { | |
return function(req, res, next) { | |
if (!req.session) { | |
req.session = {}; | |
} | |
if (!req.session.cart) { | |
req.session.cart = { | |
sum_total: 0, | |
products: [] | |
}; | |
} | |
res.send({ | |
cart: req.session.cart | |
}); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment