-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproducts.js
More file actions
77 lines (59 loc) · 1.91 KB
/
products.js
File metadata and controls
77 lines (59 loc) · 1.91 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
const Product = require('../models/product')
const getAllProductsStatic = async (req, res) => {
const products = await Product.find({price: {$gt: 30}})
.sort('price')
.select('name price');
res.status(200).json({nbHits: products.length, products})
}
const getAllProducts = async (req, res) => {
const {featured, company, name, sort, fields, numericFilters} = req.query;
const queryObject = {};
if (featured) {
queryObject.featured = featured === 'true';
}
if (company) {
queryObject.company = company;
}
if (name) {
queryObject.name = {$regex: name, $options: 'i'};
}
if (numericFilters) {
const operatorMap = {
'>': '$gt',
'>=': '$gte',
'=': '$eq',
'<': '$lt',
'<=': '$lte'
}
const regEx = /\b(<|>|>=|=|<|<=)\b/g;
let filters = numericFilters.replace(regEx, (match) => `-${operatorMap[match]}-`);
const options = ['price', 'rating'];
filters.split(',').forEach((item) => {
const [field, operator, value] = item.split('-')
if (options.includes(field)) {
queryObject[field] = {[operator]: Number(value)}
}
})
}
let result = Product.find(queryObject)
if (sort) {
const sortList = sort.split(',').join(' ');
result = result.sort(sortList)
} else {
result = result.sort('createdAt')
}
if (fields) {
const fieldsList = fields.split(',').join(' ');
result = result.select(fieldsList)
}
const page = Number(req.query.page) || 1;
const limit = Number(req.query.limit) || 10;
const skip = (page - 1) * limit;
result = result.skip(skip).limit(limit)
const products = await result;
res.status(200).json({nbHits: products.length, products})
}
module.exports = {
getAllProducts,
getAllProductsStatic
}