zkt25/z2/shop/controllers/shop.js

128 lines
3.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const Product = require('../models/product');
const Order = require('../models/order');
exports.getProducts = (req, res, next) => {
Product.find()
.then(products => {
console.log(products);
res.render('shop/product-list', {
prods: products,
pageTitle: 'All Products',
path: '/products'
});
})
.catch(err => {
console.log(err);
});
};
exports.getProduct = (req, res, next) => {
const prodId = req.params.productId;
Product.findById(prodId)
.then(product => {
res.render('shop/product-detail', {
product: product,
pageTitle: product.title,
path: '/products'
});
})
.catch(err => console.log(err));
};
exports.getIndex = (req, res, next) => {
Product.find()
.then(products => {
res.render('shop/index', {
prods: products,
pageTitle: 'Shop',
path: '/'
});
})
.catch(err => {
console.log(err);
});
};
exports.getCart = async (req, res, next) => {
try {
// populate() now returns a Promise in Mongoose 6+
const userPop = await req.user.populate('cart.items.productId');
// drop any cartitems whose product was deleted
const cartItems = userPop.cart.items.filter(item => item.productId);
const products = cartItems.map(item => ({
productId: item.productId._id,
title: item.productId.title,
price: item.productId.price,
imageUrl: item.productId.imageUrl,
quantity: item.quantity
}));
res.render('shop/cart', {
pageTitle: 'Your Cart',
path: '/cart',
products
});
} catch (err) {
next(err);
}
};
exports.postCart = (req, res, next) => {
const prodId = req.body.productId;
Product.findById(prodId)
.then(product => {
return req.user.addToCart(product);
})
.then(result => {
console.log(result);
res.redirect('/cart');
});
};
exports.postCartDeleteProduct = (req, res, next) => {
const prodId = req.body.productId;
req.user
.removeFromCart(prodId)
.then(result => {
res.redirect('/cart');
})
.catch(err => console.log(err));
};
exports.postOrder = (req, res, next) => {
req.user
.populate('cart.items.productId')
.execPopulate()
.then(user => {
const products = user.cart.items.map(i => {
return { quantity: i.quantity, product: { ...i.productId._doc } };
});
const order = new Order({
user: {
name: req.user.name,
userId: req.user
},
products: products
});
return order.save();
})
.then(result => {
return req.user.clearCart();
})
.then(() => {
res.redirect('/orders');
})
.catch(err => console.log(err));
};
exports.getOrders = (req, res, next) => {
Order.find({ 'user.userId': req.user._id })
.then(orders => {
res.render('shop/orders', {
path: '/orders',
pageTitle: 'Your Orders',
orders: orders
});
})
.catch(err => console.log(err));
};