forked from Nsanjayboruds/RIVETO
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproductController.js
More file actions
216 lines (189 loc) · 5.7 KB
/
Copy pathproductController.js
File metadata and controls
216 lines (189 loc) · 5.7 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
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import uploadOnCloudinary from "../config/Cloudinary.js";
import Product from "../model/productModel.js";
import { emitActivity } from "../services/notificationService.js";
import Review from "../model/reviewModel.js";
const safeUpload = async (fileArray) => {
const filePath = fileArray?.[0]?.path;
// If no file was uploaded for this field, safely return null
if (!filePath) {
return null;
}
// Await the Cloudinary upload
const uploadResult = await uploadOnCloudinary(filePath);
// If Cloudinary fails and returns undefined/null, throw an error
if (!uploadResult) {
throw new Error("Image upload to Cloudinary failed");
}
return uploadResult;
};
export const addProduct = async (req, res) => {
console.log("✅ Request files:", req.files);
try {
const {
name,
description,
price,
category,
subCategory,
sizes,
bestseller,
} = req.body;
console.log("✅ Request body:", req.body);
// Upload images in parallel and tolerate missing files.
const [image1, image2, image3, image4] = await Promise.all([
safeUpload(req.files?.image1),
safeUpload(req.files?.image2),
safeUpload(req.files?.image3),
safeUpload(req.files?.image4),
]);
// Validate price before creating the product.
const priceNumber = Number(price);
if (price === undefined || price === null || Number.isNaN(priceNumber)) {
return res.status(400).json({
success: false,
message: "Invalid price. A numeric value is required.",
errors: [],
});
}
// Safely parse sizes; handle invalid JSON or missing sizes gracefully.
let parsedSizes = [];
if (sizes) {
if (typeof sizes === "string") {
try {
parsedSizes = JSON.parse(sizes);
if (!Array.isArray(parsedSizes)) {
return res.status(400).json({
success: false,
message: "Invalid sizes: expected a JSON array.",
errors: [],
});
}
} catch (parseError) {
console.error("❌ Invalid sizes JSON in addProduct:", parseError);
return res.status(400).json({
success: false,
message: "Invalid sizes JSON.",
errors: [],
});
}
} else if (Array.isArray(sizes)) {
parsedSizes = sizes;
} else {
return res.status(400).json({
success: false,
message: "Invalid sizes: expected an array or JSON string.",
errors: [],
});
}
}
const productData = {
name,
description,
price: priceNumber,
category,
subCategory,
sizes: parsedSizes,
bestseller: bestseller === "true",
...(image1 ? { image1 } : {}),
...(image2 ? { image2 } : {}),
...(image3 ? { image3 } : {}),
...(image4 ? { image4 } : {}),
};
const createdProduct = await Product.create(productData);
emitActivity({
type: "product_added",
user: {
name: "Admin",
},
action: `Added product "${createdProduct.name}"`,
});
return res.status(201).json(createdProduct);
} catch (error) {
console.error("❌ Error in addProduct:", error);
return res.status(500).json({
success: false,
message: "Internal server error",
errors: [error.message],
});
}
};
export default addProduct;
export const listProducts = async (req, res) => {
try {
const page = Math.max(1, Number(req.query.page) || 1);
const limit = Math.min(Math.max(1, Number(req.query.limit) || 20), 100);
const skip = (page - 1) * limit;
const { category, subCategory, minPrice, maxPrice, search, sort } = req.query;
const filter = {};
if (category) filter.category = category;
if (subCategory) filter.subCategory = subCategory;
if (minPrice || maxPrice) {
filter.price = {};
if (minPrice) filter.price.$gte = Number(minPrice);
if (maxPrice) filter.price.$lte = Number(maxPrice);
}
if (search) filter.name = { $regex: search, $options: "i" };
const sortMap = {
price_asc: { price: 1 },
price_desc: { price: -1 },
newest: { createdAt: -1 },
};
const sortOption = sortMap[sort] || { _id: 1 };
const [products, total] = await Promise.all([
Product.find(filter).sort(sortOption).skip(skip).limit(limit).lean(),
Product.countDocuments(filter),
]);
const productsWithReviewCount = await Promise.all(
products.map(async (product) => {
const reviewCount = await Review.countDocuments({
productId: product._id,
});
return {
...product,
reviewCount,
};
})
);
return res.status(200).json({
products : productsWithReviewCount,
pagination: {
page,
limit,
total,
pages: Math.ceil(total / limit),
},
});
} catch (error) {
console.error("❌ Error in listProducts:", error);
return res.status(500).json({
success: false,
message: "Internal server error",
errors: [error.message],
});
}
};
export const removeProduct = async (req, res) => {
try {
let { id } = req.params;
const product = await Product.findByIdAndDelete(id);
if (product) {
emitActivity({
type: "product_deleted",
user: {
name: "Admin",
},
action: `Deleted product "${product.name}"`,
});
}
return res
.status(200)
.json({ message: "Product deleted successfully", product });
} catch (error) {
console.error("❌ Error in removeProduct:", error);
return res.status(500).json({
success: false,
message: "Internal server error",
errors: [error.message],
});
}
};