-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapiFeatures.js
60 lines (49 loc) · 1.47 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
55
56
57
58
59
60
class APIFeatures {
constructor(query, queryString) {
this.query = query;
this.queryString = queryString;
}
filter() {
// BUILD QUERY
// 1A) Filtering
const queryObj = { ...this.queryString };
const excludeFields = ['page', 'sort', 'limit', 'fields'];
excludeFields.forEach(el => delete queryObj[el]);
// 1B) Advanced filtering
let queryStr = JSON.stringify(queryObj);
queryStr = queryStr.replace(/\b(gte|gt|lte|lt)\b/g, match => `$${match}`);
// console.log(JSON.parse(queryStr));
this.query.find(JSON.parse(queryStr));
return this;
}
sort() {
// 2) Sorting = Classificação
if (this.queryString.sort) {
console.log(this.queryString.sort);
const sortBy = this.queryString.sort.split(',').join(' ');
this.query = this.query.sort(sortBy);
} else {
this.query = this.query.sort('-createdAd');
}
return this;
}
limitFields() {
// 3) Field limiting = Limitação de campo
if (this.queryString.fields) {
const fields = this.queryString.fields.split(',').join(' ');
this.query = this.query.select(fields);
} else {
this.query = this.query.select('-__v');
}
return this;
}
paginate() {
// 4) Pagination
const page = this.queryString.page * 1 || 1;
const limit = this.queryString.limit * 1 || 100;
const skip = (page - 1) * limit;
this.query = this.query.skip(skip).limit(limit);
return this;
}
}
module.exports = APIFeatures;