zkt25/z2/shop/controllers/admin.js

94 lines
2.6 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');
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 errorhandler (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 nonexistent 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);
}
};