94 lines
2.6 KiB
JavaScript
94 lines
2.6 KiB
JavaScript
const Product = require('../models/product');
|
||
|
||
exports.getAddProduct = (req, res, next) => {
|
||
res.render('admin/edit-product', {
|
||
pageTitle: 'Add Product',
|
||
path: '/admin/add-product',
|
||
editing: false
|
||
});
|
||
};
|
||
|
||
exports.postAddProduct = async (req, res, next) => {
|
||
try {
|
||
console.log('§ postAddProduct ➡️', req.body);
|
||
const { title, imageUrl, price, description } = req.body;
|
||
const product = new Product({ title, price, description, imageUrl });
|
||
await product.save();
|
||
console.log('✓ Product saved:', product._id);
|
||
return res.redirect('/admin/products');
|
||
} catch (err) {
|
||
console.error('✗ Error in postAddProduct:', err);
|
||
next(err); // this will trigger your error‐handler (or crash if none)
|
||
}
|
||
};
|
||
|
||
exports.getEditProduct = (req, res, next) => {
|
||
const editMode = req.query.edit;
|
||
if (!editMode) {
|
||
return res.redirect('/');
|
||
}
|
||
const prodId = req.params.productId;
|
||
Product.findById(prodId)
|
||
.then(product => {
|
||
if (!product) {
|
||
return res.redirect('/');
|
||
}
|
||
res.render('admin/edit-product', {
|
||
pageTitle: 'Edit Product',
|
||
path: '/admin/edit-product',
|
||
editing: editMode,
|
||
product: product
|
||
});
|
||
})
|
||
.catch(err => console.log(err));
|
||
};
|
||
|
||
exports.postEditProduct = async (req, res, next) => {
|
||
try {
|
||
console.log('§ postEditProduct ➡️', req.body);
|
||
const { productId, title, imageUrl, price, description } = req.body;
|
||
const product = await Product.findById(productId);
|
||
if (!product) {
|
||
console.warn('!! Tried to edit non‑existent product:', productId);
|
||
return res.redirect('/admin/products');
|
||
}
|
||
product.title = title;
|
||
product.price = price;
|
||
product.description = description;
|
||
product.imageUrl = imageUrl;
|
||
await product.save();
|
||
console.log('✓ Product updated:', product._id);
|
||
return res.redirect('/admin/products');
|
||
} catch (err) {
|
||
console.error('✗ Error in postEditProduct:', err);
|
||
next(err);
|
||
}
|
||
};
|
||
|
||
exports.getProducts = (req, res, next) => {
|
||
Product.find()
|
||
// .select('title price -_id')
|
||
// .populate('userId', 'name')
|
||
.then(products => {
|
||
console.log(products);
|
||
res.render('admin/products', {
|
||
prods: products,
|
||
pageTitle: 'Admin Products',
|
||
path: '/admin/products'
|
||
});
|
||
})
|
||
.catch(err => console.log(err));
|
||
};
|
||
|
||
exports.postDeleteProduct = async (req, res, next) => {
|
||
try {
|
||
const prodId = req.body.productId;
|
||
// Mongoose 6+: use findByIdAndDelete
|
||
await Product.findByIdAndDelete(prodId);
|
||
return res.redirect('/admin/products');
|
||
} catch (err) {
|
||
console.error(err);
|
||
next(err);
|
||
}
|
||
};
|