diff options
author | Mateja <mail@matejamaric.com> | 2021-07-11 18:04:43 +0200 |
---|---|---|
committer | Mateja <mail@matejamaric.com> | 2021-07-11 18:05:13 +0200 |
commit | 587e9aa95825b6e62e33c801c5367877ed0ec230 (patch) | |
tree | 9a9f739d03f641b21b216b969a6a148ac665070f | |
parent | 54619e571698a89727fa1112290addcf2f8c82da (diff) | |
download | mevn-ecommerce-587e9aa95825b6e62e33c801c5367877ed0ec230.tar.gz mevn-ecommerce-587e9aa95825b6e62e33c801c5367877ed0ec230.zip |
Finished products controller.
-rw-r--r-- | server/.gitignore | 1 | ||||
-rw-r--r-- | server/controllers/products.js | 55 |
2 files changed, 48 insertions, 8 deletions
diff --git a/server/.gitignore b/server/.gitignore index 37d7e73..6749f3a 100644 --- a/server/.gitignore +++ b/server/.gitignore @@ -1,2 +1,3 @@ node_modules .env +uploads/* diff --git a/server/controllers/products.js b/server/controllers/products.js index 6265e27..e039dac 100644 --- a/server/controllers/products.js +++ b/server/controllers/products.js @@ -1,23 +1,62 @@ +const Product = require('../models/Product'); + module.exports = { - index(req, res) { - res.json({products: "index"}); + async index(req, res) { + const posts = await Product.find({}, '_id name imagePath price'); + res.json(posts); }, - show(req, res) { - res.json({products: "show"}); + async show(req, res) { + const post = await Product.findOne({_id: req.params.id}, '_id name description imagePath price'); + res.json(post); }, store(req, res) { - res.json({products: "store"}); + let newProductObj = { + name: req.body.name, + description: req.body.description, + //imagePath: null, + price: req.body.price + }; + if (req.file) + newProductObj.imagePath = req.file.path; + + const newProduct = new Product(newProductObj); + newProduct.save() + .then(() => res.json({status: "Product successfully added!"})) + .catch(error => res.json({ + status: "Couldn't add product!", + error + })); }, update(req, res) { - res.json({products: "update"}); + let updatedProduct = { + name: req.body.name, + description: req.body.description, + //imagePath: null, + price: req.body.price + }; + + if (req.file) + updatedProduct.imagePath = req.file.path; + + Product.findOneAndUpdate({_id: req.params.id}, {$set: updatedProduct}, {new: true}, (error, product) => { + if (error) + res.json({status: "Couldn't update product!", error}); + else + res.json({status: "Successfully updated product!", product}); + }); }, destroy(req, res) { - res.json({products: "destroy"}); - }, + Product.findByIdAndRemove(req.params.id, (error, product) => { + if (error) + res.json({status: "Error when removing product!", error}); + else + res.json({status: "Product successfully removed!", product}) + }); + } }; |