-
Notifications
You must be signed in to change notification settings - Fork 15
/
category.js
75 lines (73 loc) · 2.16 KB
/
category.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
const Category = require("../model/categories");
const ObjectID = require("mongodb").ObjectID;
module.exports.getAllCategories = (req, res) => {
try {
Category.find()
.then((products) => {
res.json(products);
})
.catch((err) => console.log(err));
} catch (err) {
res.status(500).send(err);
}
};
module.exports.categoryDetail = async (req, res) => {
if (req.params.id == null || !ObjectID.isValid(req.params.id)) {
return res.json({
status: "error",
message: "Valid Category Id required",
});
}
try {
const category = await Category.findById(req.params.id);
return res.status(200).send(category);
} catch (err) {
res.status(500).send(err);
}
};
module.exports.addCategory = async (req, res) => {
try {
const category = new Category({
name: req.body.name,
description: req.body.description ? req.body.description : "",
image: req.body.image ? req.body.image : "",
});
const newCategory = await category.save();
res.json(newCategory);
} catch (err) {
res.status(500).send(err);
}
};
module.exports.editCategory = async (req, res) => {
const id = req.params.categoryId;
const categoryInputValue = req.body;
try {
const category = await Category.findOneAndUpdate(
{
_id: id,
},
categoryInputValue,
{
new: true,
runValidators: true,
context: "query",
},
);
if (!category) return res.status(404).send("Product Not Found");
res.send(category);
} catch (err) {
res.status(500).send(err);
}
};
module.exports.deleteCategory = async (req, res) => {
const id = req.params.categoryId;
try {
const category = await Category.findByIdAndDelete({
_id: id,
});
if (!category) return res.status(404).send("Product Not Found");
res.send({ message: "Deleted Successfully " });
} catch (err) {
res.status(500).send(err);
}
};