aboutsummaryrefslogtreecommitdiff
path: root/server/controllers/products.js
blob: 12a2340f6950833aa931f23f00df0965749db3f9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const Product = require('../models/Product');

module.exports = {

  async index(req, res) {
    const posts = await Product.find({}, '_id name imagePath price');
    res.json(posts);
  },

  async show(req, res) {
    const post = await Product.findOne({_id: req.params.id}, '_id name description imagePath price');
    res.json(post);
  },

  store(req, res) {
    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.status(400).json({
        status: "Couldn't add product!",
        error
      }));
  },

  update(req, res) {
    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.status(400).json({status: "Couldn't update product!", error});
      else
        res.json({status: "Successfully updated product!", product});
    });
  },

  destroy(req, res) {
    Product.findByIdAndRemove(req.params.id, (error, product) => {
      if (error)
        res.status(400).json({status: "Error when removing product!", error});
      else
        res.json({status: "Product successfully removed!", product})
    });
  }

};