-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproductController.js
More file actions
161 lines (123 loc) · 4.24 KB
/
productController.js
File metadata and controls
161 lines (123 loc) · 4.24 KB
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
import asyncHandler from '../middleware/asyncHandler.js';
import Product from '../models/productModel.js';
// @desc Fetch all products
// @route GET /api/products
// @access Public
const getProducts = asyncHandler(async (req, res) => {
const pageSize = process.env.PAGINATION_LIMIT || 8;
const page = Number(req.query.pageNumber) || 1;
const keyword = req.query.keyword ? {name: { $regex: req.query.keyword, $options: 'i' }} : {};
const count = await Product.countDocuments({...keyword});
const products = await Product.find({...keyword})
.limit(pageSize)
.skip(pageSize * (page - 1));
res.json({products, page, pages: Math.ceil(count / pageSize)});
});
// @desc Create a product
// @route POST /api/products
// @access Private/Admin
const createProduct = asyncHandler(async (req, res) => {
const product = new Product({
name: 'Sample name',
price: 0,
user: req.user._id,
image: '/images/sample.jpg',
brand: 'Sample brand',
category: 'Sample category',
countInStock: 0,
numReviews: 0,
description: 'Sample description'
});
const createdProduct = await product.save();
res.status(201).json(createdProduct);
});
// @desc Fetch single product
// @route GET /api/products/:id
// @access Public
const getProductById = asyncHandler(async (req, res) => {
const product = await Product.findById(req.params.id);
if (product) {
return res.json(product);
} else {
res.status(404);
throw new Error('Resource not found');
}
});
// @desc Update a product
// @route PUT /api/products/:id
// @access Private/Admin
const updateProduct = asyncHandler(async (req, res) => {
const { name, price, description, image, brand, category, countInStock } = req.body;
const product = await Product.findById(req.params.id);
if (product) {
product.name = name;
product.price = price;
product.description = description;
product.image = image;
product.brand = brand;
product.category = category;
product.countInStock = countInStock;
const updatedProduct = await product.save();
res.json(updatedProduct);
} else {
res.status(404);
throw new Error('Product not found');
}
});
// @desc Delete a product
// @route DELETE /api/products/:id
// @access Private/Admin
const deleteProduct = asyncHandler(async (req, res) => {
const product = await Product.findById(req.params.id);
if (product) {
await Product.deleteOne({_id: product._id});
res.status(200).json({message: 'Product deleted successfully'});
} else {
res.status(404);
throw new Error('Product not found');
}
});
// @desc Create a new review
// @route POST /api/products/:id/reviews
// @access Private
const createProductReview = asyncHandler(async (req, res) => {
const { rating, comment } = req.body;
const product = await Product.findById(req.params.id);
if (product) {
const alreadyReviewed = product.reviews.find(review => review.user.toString() === req.user._id.toString());
if (alreadyReviewed) {
res.status(400);
throw new Error('Product already reviewed');
}
const review = {
name: req.user.name,
rating: Number(rating),
comment,
user: req.user._id
};
product.reviews.push(review);
product.numReviews = product.reviews.length;
product.rating = product.reviews.reduce((acc, item) => item.rating + acc, 0) / product.reviews.length;
await product.save();
res.status(201).json({message: 'Review added'});
} else {
res.status(404);
throw new Error('Product not found');
}
});
// @desc Get top rated products
// @route GET /api/products/top
// @access Public
const getTopProducts = asyncHandler(async (req, res) => {
const products = await Product.find({}).sort({rating: -1}).limit(3);
res.status(200).json(products);
});
export {
getProducts,
getProductById,
createProduct,
updateProduct,
deleteProduct,
createProductReview,
getTopProducts
};