-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproduct.controller.ts
340 lines (324 loc) · 8.49 KB
/
product.controller.ts
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import { Request, Response } from 'express'
import { responseSuccess, ErrorHandler } from '../utils/response'
import { ProductModel } from '../database/models/product.model'
import { STATUS } from '../constants/status'
import mongoose from 'mongoose'
import { isAdmin } from '../utils/validate'
import { uploadFile, uploadManyFile } from '../utils/upload'
import { HOST } from '../utils/helper'
import { FOLDERS, FOLDER_UPLOAD, ROUTE_IMAGE } from '../constants/config'
import fs from 'fs'
import { omitBy } from 'lodash'
import { ORDER, SORT_BY } from '../constants/product'
export const handleImageProduct = (product) => {
if (product.image !== undefined && product.image !== '') {
product.image = HOST + `/${ROUTE_IMAGE}/` + product.image
}
if (product.images !== undefined && product.images.length !== 0) {
product.images = product.images.map((image) => {
return image !== '' ? HOST + `/${ROUTE_IMAGE}/` + image : ''
})
}
return product
}
const removeImageProduct = (image) => {
if (image !== undefined && image !== '') {
fs.unlink(`${FOLDER_UPLOAD}/${FOLDERS.PRODUCT}/${image}`, (err) => {
if (err) console.error(err)
})
}
}
const removeManyImageProduct = (images: string[]) => {
if (images !== undefined && images.length > 0) {
images.forEach((image) => {
removeImageProduct(image)
})
}
}
const addProduct = async (req: Request, res: Response) => {
const form: Product = req.body
const {
name,
description,
category,
image,
images,
price,
rating,
price_before_discount,
quantity,
sold,
view,
} = form
const product = {
name,
description,
category,
image,
images,
price,
rating,
price_before_discount,
quantity,
sold,
view,
}
const productAdd = await new ProductModel(product).save()
const response = {
message: 'Tạo sản phẩm thành công',
data: productAdd.toObject({
transform: (doc, ret, option) => {
delete ret.__v
return handleImageProduct(ret)
},
}),
}
return responseSuccess(res, response)
}
const getProducts = async (req: Request, res: Response) => {
let {
page = 1,
limit = 30,
category,
exclude,
sort_by,
order,
rating_filter,
price_max,
price_min,
name,
} = req.query as {
[key: string]: string | number
}
page = Number(page)
limit = Number(limit)
let condition: any = {}
if (category) {
condition.category = category
}
if (exclude) {
condition._id = { $ne: exclude }
}
if (rating_filter) {
condition.rating = { $gte: rating_filter }
}
if (price_max) {
condition.price = {
$lte: price_max,
}
}
if (price_min) {
condition.price = condition.price
? { ...condition.price, $gte: price_min }
: { $gte: price_min }
}
if (!ORDER.includes(order as string)) {
order = ORDER[0]
}
if (!SORT_BY.includes(sort_by as string)) {
sort_by = SORT_BY[0]
}
if (name) {
condition.name = {
$regex: name,
$options: 'i',
}
}
let [products, totalProducts]: [products: any, totalProducts: any] =
await Promise.all([
ProductModel.find(condition)
.populate({
path: 'category',
})
.sort({ [sort_by]: order === 'desc' ? -1 : 1 })
.skip(page * limit - limit)
.limit(limit)
.select({ __v: 0, description: 0 })
.lean(),
ProductModel.find(condition).countDocuments().lean(),
])
products = products.map((product) => handleImageProduct(product))
const page_size = Math.ceil(totalProducts / limit) || 1
const response = {
message: 'Lấy các sản phẩm thành công',
data: {
products,
pagination: {
page,
limit,
page_size,
},
},
}
return responseSuccess(res, response)
}
const getAllProducts = async (req: Request, res: Response) => {
let { category } = req.query
let condition = {}
if (category) {
condition = { category: category }
}
let products: any = await ProductModel.find(condition)
.populate({ path: 'category' })
.sort({ createdAt: -1 })
.select({ __v: 0, description: 0 })
.lean()
products = products.map((product) => handleImageProduct(product))
const response = {
message: 'Lấy tất cả sản phẩm thành công',
data: products,
}
return responseSuccess(res, response)
}
const getProduct = async (req: Request, res: Response) => {
let condition = { _id: req.params.product_id }
const productDB: any = await ProductModel.findOneAndUpdate(
condition,
{ $inc: { view: 1 } },
{ new: true }
)
.populate('category')
.select({ __v: 0 })
.lean()
if (productDB) {
const response = {
message: 'Lấy sản phẩm thành công',
data: handleImageProduct(productDB),
}
return responseSuccess(res, response)
} else {
throw new ErrorHandler(STATUS.NOT_FOUND, 'Không tìm thấy sản phẩm')
}
}
const updateProduct = async (req: Request, res: Response) => {
const form: Product = req.body
const {
name,
description,
category,
image,
rating,
price,
images,
price_before_discount,
quantity,
sold,
view,
} = form
const product = omitBy(
{
name,
description,
category,
image,
rating,
price,
images,
price_before_discount,
quantity,
sold,
view,
},
(value) => value === undefined || value === ''
)
const productDB = await ProductModel.findByIdAndUpdate(
req.params.product_id,
product,
{
new: true,
}
)
.select({ __v: 0 })
.lean()
if (productDB) {
const response = {
message: 'Cập nhật sản phẩm thành công',
data: handleImageProduct(productDB),
}
return responseSuccess(res, response)
} else {
throw new ErrorHandler(STATUS.NOT_FOUND, 'Không tìm thấy sản phẩm')
}
}
const deleteProduct = async (req: Request, res: Response) => {
const product_id = req.params.product_id
const productDB: any = await ProductModel.findByIdAndDelete(product_id).lean()
if (productDB) {
removeImageProduct(productDB.image)
removeManyImageProduct(productDB.images)
return responseSuccess(res, { message: 'Xóa thành công' })
} else {
throw new ErrorHandler(STATUS.NOT_FOUND, 'Không tìm thấy sản phẩm')
}
}
const deleteManyProducts = async (req: Request, res: Response) => {
const list_id = (req.body.list_id as string[]).map((id: string) =>
mongoose.Types.ObjectId(id)
)
const productDB: any = await ProductModel.find({
_id: { $in: list_id },
}).lean()
const deletedData = await ProductModel.deleteMany({
_id: { $in: list_id },
}).lean()
productDB.forEach((product) => {
removeImageProduct(product.image)
removeManyImageProduct(product.images)
})
if (productDB.length > 0) {
return responseSuccess(res, {
message: `Xóa ${deletedData.deletedCount} sản phẩm thành công`,
data: { deleted_count: deletedData.deletedCount },
})
} else {
throw new ErrorHandler(STATUS.NOT_FOUND, 'Không tìm thấy sản phẩm')
}
}
const searchProduct = async (req: Request, res: Response) => {
let { searchText }: { [key: string]: string | any } = req.query
searchText = decodeURI(searchText)
let condition = { $text: { $search: `\"${searchText}\"` } }
if (!isAdmin(req)) {
condition = Object.assign(condition, { visible: true })
}
let products: any = await ProductModel.find(condition)
.populate('category')
.sort({ createdAt: -1 })
.select({ __v: 0, description: 0 })
.lean()
products = products.map((product) => handleImageProduct(product))
const response = {
message: 'Tìm các sản phẩm thành công',
data: products,
}
return responseSuccess(res, response)
}
const uploadProductImage = async (req: Request, res: Response) => {
const path = await uploadFile(req, FOLDERS.PRODUCT)
const response = {
message: 'Upload ảnh thành công',
data: path,
}
return responseSuccess(res, response)
}
const uploadManyProductImages = async (req: Request, res: Response) => {
const paths = await uploadManyFile(req, FOLDERS.PRODUCT)
const response = {
message: 'Upload các ảnh thành công',
data: paths,
}
return responseSuccess(res, response)
}
const ProductController = {
addProduct,
getAllProducts,
getProducts,
getProduct,
updateProduct,
deleteProduct,
searchProduct,
deleteManyProducts,
uploadProductImage,
uploadManyProductImages,
}
export default ProductController