You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.5 KiB
JavaScript
53 lines
1.5 KiB
JavaScript
11 months ago
|
// productController.js
|
||
|
const Product = require('../model/Product');
|
||
|
|
||
|
// Controller function for creating a product (accessible only by isAdmin)
|
||
|
exports.createProduct = async (req, res) => {
|
||
|
try {
|
||
|
// Check if the user is an admin
|
||
|
if (!req.user.isAdmin) {
|
||
|
return res.status(403).json({ message: 'Permission denied. Only admins can create products.' });
|
||
|
}
|
||
|
|
||
|
const { name, description, price, isActive } = req.body;
|
||
|
|
||
|
const newProduct = new Product({
|
||
|
name,
|
||
|
description,
|
||
|
price,
|
||
|
isActive,
|
||
|
});
|
||
|
|
||
|
await newProduct.save();
|
||
|
|
||
|
res.status(201).json({ message: 'Product created successfully' });
|
||
|
} catch (error) {
|
||
|
console.error(error);
|
||
|
res.status(500).json({ message: 'Internal server error' });
|
||
|
}
|
||
|
};
|
||
|
|
||
|
// Controller function for retrieving all products (accessible to both admin and normal user)
|
||
|
exports.getAllProducts = async (req, res) => {
|
||
|
try {
|
||
|
const products = await Product.find();
|
||
|
|
||
|
res.status(200).json(products);
|
||
|
} catch (error) {
|
||
|
console.error(error);
|
||
|
res.status(500).json({ message: 'Internal server error' });
|
||
|
}
|
||
|
};
|
||
|
|
||
|
// Controller function for retrieving all active products (accessible to both admin and normal user)
|
||
|
exports.getActiveProducts = async (req, res) => {
|
||
|
try {
|
||
|
const activeProducts = await Product.find({ isActive: true });
|
||
|
|
||
|
res.status(200).json(activeProducts);
|
||
|
} catch (error) {
|
||
|
console.error(error);
|
||
|
res.status(500).json({ message: 'Internal server error' });
|
||
|
}
|
||
|
};
|