Last active
December 11, 2019 19:50
-
-
Save paulobunga/508afe475530d2788336b491a41b576d to your computer and use it in GitHub Desktop.
Product controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Product = require('./product_model'); | |
module.exports = { | |
getProducts: async (req, res, next) => { | |
Product.find({}).exec((error, result) => { | |
if (error) { | |
return next(error); | |
} | |
if (result) { | |
if (result.length > 0) { | |
res.status(200).json({ status: 'SUCCESS', products: result }); | |
} else { | |
res.status(200).json({ status: 'NO_PRODUCTS' }); | |
} | |
} | |
}); | |
}, | |
getProduct: async (req, res, next) => { | |
let productId = req.params.productId; | |
Product.findById(productId, (error, result) => { | |
if (error) { | |
return next(error); | |
} | |
if (result) { | |
res.status(200).json({ status: 'SUCCESS', product: result }); | |
} else | |
{ | |
return res.json( { status: 'FAILED', message: 'Product not found' } ); | |
} | |
}); | |
}, | |
addProduct: async (req, res, next) => { | |
let { name, quantity, cost_price, sale_price } = req.body; | |
let product = new Product({ | |
name, | |
quantity, | |
cost_price, | |
sale_price, | |
}); | |
product.save((error, result) => { | |
if (error) { | |
return next(error); | |
} | |
if (result) { | |
return res.json({ | |
status: 'SUCCESS', | |
message: 'Product added successfully', | |
}); | |
} else | |
{ | |
return res.json( { | |
status: 'FAILED', | |
message: 'Unable to add product' | |
} ); | |
} | |
}); | |
}, | |
updateProduct: async (req, res, next) => { | |
let productId = req.params.productId; | |
let { name, quantity, cost_price, sale_price } = req.body; | |
Product.findOneAndUpdate( | |
{ _id: productId }, | |
{ name, quantity, cost_price, sale_price } | |
).exec((error, result) => { | |
if (error) { | |
return next(error); | |
} | |
if (result) { | |
return res.json({ | |
status: 'SUCCESS', | |
message: 'Product updated successfully', | |
}); | |
} else | |
{ | |
return res.json( { | |
status: 'FAILED', | |
message: 'Product not updated' | |
}) | |
} | |
}); | |
}, | |
deleteProduct: async (req, res, next) => { | |
let productId = req.params.productId; | |
Product.findOneAndDelete({ _id: productId }, (error, result) => { | |
if (error) { | |
return next(error); | |
} | |
if (result) { | |
return res.json({ | |
status: 'SUCCESS', | |
messgae: 'Product deleted successfully', | |
}); | |
} | |
}); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment