Skip to content

Instantly share code, notes, and snippets.

@paulobunga
Created December 18, 2019 00:27
Show Gist options
  • Save paulobunga/56689f509ebfbcfa6581d6787558c3a7 to your computer and use it in GitHub Desktop.
Save paulobunga/56689f509ebfbcfa6581d6787558c3a7 to your computer and use it in GitHub Desktop.
Complete controller code
const Product = require('./product_model');
module.exports.createProduct = async (req, res, next) => {
const { name, sale_price, cost_price, quantity } = req.body;
const newProduct = new Product({
name,
sale_price,
cost_price,
quantity,
});
newProduct.save((error, result) => {
if (error) {
res.json({ status: 'ERROR', message: 'Error creating product' });
}
if (result) {
res.json({ status: 'SUCCESS', message: 'Product created' });
} else {
res.json({ status: 'FAILURE', message: 'Failed to create product' });
}
});
};
module.exports.viewProducts = async (req, res, next) => {
Product.find({}).exec((error, result) => {
if (error) {
res.json({ status: 'ERROR', message: 'Error getting products' });
}
if (result.length > 0) {
res.json({
status: 'SUCCESS',
message: 'Products found',
products: result,
});
} else {
res.json({ status: 'NO_PRODUCTS', message: 'No products found' });
}
});
};
module.exports.viewSingleProduct = async (req, res, next) => {
Product.findOne({ _id: req.params.productId }).exec((error, result) => {
if (error) {
res.json({ status: 'ERROR', message: 'Error getting product' });
}
if (result) {
res.json({
status: 'SUCCESS',
message: 'Product found',
product: result,
});
} else {
res.json({
status: 'NO_PRODUCT',
message: 'No product with specified product ID found',
});
}
});
};
module.exports.updateProduct = async (req, res, next) => {
Product.findOneAndUpdate(
{ _id: req.params.productId },
{
name: req.body.name,
sale_price: req.body.sale_price,
cost_price: req.body.cost_price,
quantity: req.body.quantity,
}
).exec((error, result) => {
if (error) {
res.json({ status: 'ERROR', message: 'Error updating product' });
}
if (result) {
res.json({
status: 'SUCCESS',
message: 'Product details updated successfully',
});
} else {
res.json({
status: 'FAILURE',
message: 'Failed to update product details',
});
}
});
};
module.exports.deleteProduct = async (req, res, next) => {
let { productId } = req.params;
Product.findByIdAndDelete(productId, (error, result) => {
if (error) {
res.json({ status: 'ERROR', message: 'Error deleting product' });
}
if (result) {
res.json({ status: 'SUCCESS', message: 'Product deleted' });
} else {
res.json({ status: 'FAILURE', message: 'Failed to delete product' });
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment