-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapiFeatures.js
54 lines (46 loc) · 1.3 KB
/
apiFeatures.js
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
/*
class => classes are a template of creating Objects
constructor => used to initialize object properties
class method=> class method are created with the same syntax as object method.
*/
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 };
// removing fields from the query string
const removeFields = ['keyword', 'limit', 'page'];
removeFields.forEach((el) => {
delete queryCopy[el];
});
// advaced filter for price,rating etc
let queryStr = JSON.stringify(queryCopy);
queryStr = queryStr.replace(/\b(gt|gte|lt|lte)\b/g, (match) => `$${match}`);
// find product from query
this.query = this.query.find(JSON.parse(queryStr));
return this;
}
pagination(resPerpage) {
const currentPage = Number(this.queryStr.page) || 1;
const skip = resPerpage * (currentPage - 1);
this.query = this.query.limit(resPerpage).skip(skip);
return this;
}
}
module.exports = APIFeatures;