-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiFeatures.js
More file actions
55 lines (44 loc) · 1.41 KB
/
apiFeatures.js
File metadata and controls
55 lines (44 loc) · 1.41 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
class ApiFeatures {
constructor(query, queryStr) {
this.query = query;
this.queryStr = queryStr;
}
search() {
const keyword = this.queryStr.keyword
? {
name: {
$regex: this.queryStr.keyword,
$options: "i"
}
}
: {};
this.query = this.query.find({ ...keyword });
return this;
}
filter() {
const queryCopy = { ...this.queryStr };
// Remove unwanted fields
const removeFields = ["keyword", "page", "limit"];
removeFields.forEach((key) => delete queryCopy[key]);
// Handle all price operators
const operators = ['gte', 'lte', 'gt', 'lt'];
operators.forEach(op => {
if (queryCopy[`price[${op}]`]) {
if (!queryCopy.price) queryCopy.price = {};
queryCopy.price[`$${op}`] = Number(queryCopy[`price[${op}]`]);
delete queryCopy[`price[${op}]`];
}
});
this.query = this.query.find(queryCopy);
return this;
}
pagination(resultPerPage) {
// Current Page
const currentPage = Number(this.queryStr.page) || 1
// Skip
const skip = resultPerPage * (currentPage - 1)
this.query = this.query.limit(resultPerPage).skip(skip)
return this
}
}
module.exports = ApiFeatures;