I am currently developing an ecommerce app using the MEAN stack and have encountered a recurring question regarding AJAX http requests. The single-page architecture integral to MEAN makes this question particularly significant.
I have come across advice stating that http requests should only be utilized when absolutely essential, prompting me to ponder the extent of this principle. Is it advisable to gather all pertinent information from required http requests in order to minimize subsequent requests, or does this approach risk complicating the code without yielding substantial performance benefits?
For instance, I have an addToCart function that initiates a post
request. This request first verifies the availability of the item in stock by checking the 'product' database and then confirms its absence in the user's cart by consulting the 'user' database before adding it.
Post Request:
.post(auth, function(req, res, next){
var newCartItem = {
product: req.body._id,
quantity: req.body.quantity
};
function addCartItem(){
//Checks user.cart.product to ensure that item isn't already in cart
User.update({username: req.payload.username, 'cart.product': {$ne: newCartItem.product}},
{$push: {cart: newCartItem}},
function(err, user){
if(err){return next(err);}
if(!user.nModified){
res.json({message: 'Item is already in your cart.'});
}else{
res.json({message: 'Item added to cart', addedProduct: newCartItem});
}
}
);
}
//Checks product database to ensure sufficient inventory(quantity)
Product.update({_id:req.body._id, quantity: {$gte: req.body.quantity}}, {$inc:{quantity: -req.body.quantity}},
function(err, product){
if(err) {
return next(err);
}else if(product.nModified === 0) {
res.json({message: 'Product no longer has sufficient quantity in stock.'});
}else{
addCartItem();
}
});
If my goal is to minimize http requests, one strategy could involve having the Product.update
callback furnish the client with product details (via
res.json</code), which can then be used for inventory verification on the client side prior to triggering another server request. Similarly, upon successfully adding the product to the cart, the <code>User.update
callback might send back the updated user.cart
, allowing the client-side to validate the absence of the item in the user's cart before initiating any further requests.
Initially appearing as a singular quandary, this issue has surfaced repeatedly in various scenarios. While acknowledging the subjective nature of this inquiry, I find myself faced with a fundamental question that seems pervasive across different contexts.
To sum up, my query stands thus: Is it beneficial to extract all feasible information from necessary http requests to diminish subsequent requests, or would such an approach merely result in convoluted code with minimal performance gains?
Cheers! Tyler