-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducts.js
187 lines (151 loc) · 6.4 KB
/
products.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
const express = require('express');
const router = express.Router();
const auth = require('../../middleware/auth');
const { check, validationResult } = require('express-validator')
const Product = require('../../models/Product') //Getting the ProductSchema
const User = require('../../models/User') //Getting the UserSchema
const Deleted_Product = require('../../models/Deleted_Product') //Getting the Deleted_ProductSchema
const Category = require('../../models/Category') //Getting the ProductSchema
// @router POST api/products
// @desc Add a product
// @access public
router.post('/', [
// Checking the required specifications of the entered data
check('name', 'Name is required !').not().isEmpty(),
check('description', 'Description is required !').not().isEmpty(),
check('price', 'Price is required !').not().isEmpty(),
check('category', 'Category is required !').not().isEmpty()
], auth, async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, description, price, picture, category } = req.body
const user = await User.findById(req.user.id) // returns its id only
try {
// Checking the category
const category_db = await Category.findOne({ name: category }) //short for name: name
if (!category_db) { // if it is not created before
const category_db = new Category({ name: category, user });
await category_db.save()
}
const category_id = category_db.id
//Entering values
const product = new Product({
name,
description,
price,
picture,
category_id,
user
});
await product.save() //saving to db
res.status(200).send('Product is added')
} catch (e) {
res.status(500).send(e)
}
})
// @router GET api/products/all
// @desc Get all products
// @access public
router.get('/all', async (req, res) => {
try {
const products = await Product.find().populate('product', ['name', 'picture', 'description', 'price', 'category_id', 'id']) //get the name, avatar, and phone number from the UserSchema
res.json(products);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error !')
}
})
// @router POST api/products/:id
// @desc Update a product
// @access private
router.post('/:id', auth, async (req, res) => {
const product = await Product.findById(req.params.id)
const user = await User.findById(req.user.id) // returns its id only and other times returns the obj سبحان الله
if (JSON.stringify(user.id) !== JSON.stringify(product.user)) {
return res.status(400).send('This action can be done by the product creator only')
}
const { name, description, price, picture, category } = req.body
// Checking the category
const category_db = await Category.findOne({ name: category }) //short for name: name
console.log(category_db)
if (!category_db) { // if it is not created before
const category_db = new Category({ name: category, user });
await category_db.save()
}
category_id = category_db.id
const productFields = {}
if (name) productFields.name = name;
if (description) productFields.description = description;
if (price) productFields.price = price;
if (picture) productFields.picture = picture;
if (category) productFields.category_id = category_id;
try {
// product = await Product.findOneAndUpdate({ _id: req.params.id }, { $set: productFields }, { new: true }) //NOTWORKING !!!
product.name = name;
product.description = description;
product.price = price;
product.picture = picture;
product.category_id = category_id;
res.status(200).send(product) // btege sa7 bs msh btt save !!!!!
} catch (e) {
res.status(500).send(e)
}
})
// @router DELETE api/products/:id
// @desc delete product by id
// @access Private
router.delete('/:id', auth, async (req, res) => { // private --> we have token so we add middleware making it private
try {
const product = await Product.findById(req.params.id)
if (JSON.stringify(product.user) !== JSON.stringify(req.user.id)) {
return res.status(401).json({ msg: 'User not authorized' })
}
if (!product) {
return res.status(404).json({ msg: 'Product not found !' })
}
const { name, description, price, picture, category_id, user } = product
const deleted_product = new Deleted_Product({ name, description, price, picture, category_id, user });
await deleted_product.save() //saving to db to another collection
await product.remove() //removing from db
res.json('Product is removed..')
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error !')
}
})
// @desc Get all deleted products
// @access public
router.get('/all/deleted_products', async (req, res) => {
try {
const deleted_products = await Deleted_Product.find().populate('product', ['name', 'picture', 'description', 'price', 'category', 'id']) //get the name, avatar, and phone number from the UserSchema
res.json(deleted_products);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error !')
}
})
// @router POST api/products/deleted_products/:id
// @desc retrieve delted product by id
// @access Private
router.post('/deleted_products/:id', auth, async (req, res) => {
try {
const deleted_product = await Deleted_Product.findById(req.params.id)
if (JSON.stringify(deleted_product.user) !== JSON.stringify(req.user.id)) {
return res.status(401).json({ msg: 'User not authorized' })
}
if (!deleted_product) {
return res.status(404).json({ msg: 'Product not found !' })
}
const { name, description, price, picture, category, user } = deleted_product
const product = new Product({ name, description, price, picture, category, user });
await product.save() //saving to db to another collection
await deleted_product.remove() //removing from db
res.json('Product is retrieved..')
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error !')
}
})
module.exports = router;