-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiFeatures.js
More file actions
60 lines (55 loc) · 1.88 KB
/
Copy pathapiFeatures.js
File metadata and controls
60 lines (55 loc) · 1.88 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
export default class APIFeatures {
constructor(query, requestData, filter = {}) {
this.query = query.find(filter);
this.requestData = requestData;
}
filter() {
const queryObj = { ...this.requestData };
const excludedFields = ["page", "sort", "limit", "fields"];
excludedFields.forEach((el) => delete queryObj[el]);
let queryStr = JSON.stringify(queryObj);
queryStr = queryStr.replace(/\b(gte|gt|lte|lt)\b/g, (match) => `$${match}`);
let where = JSON.parse(queryStr);
where = Object.keys(where).length == 0 ? null : where;
// console.log(where);
if (where == null) {
this.query.find();
} else {
this.query.find(where);
}
return this;
}
sort() {
const sort = this.requestData.sort == null ? null : this.requestData.sort.split(",").join(" ");
if (sort != null) {
this.query.sort(sort);
}
return this;
}
limitedFields() {
const fields = this.requestData.fields == null ? null : this.requestData.fields.split(",").join(" ");
if (fields == null) {
this.query.select("-__v");
} else {
this.query.select(fields);
}
return this;
}
pagination() {
const page = this.requestData.page == null ? null : this.requestData.page * 1 || 1;
const limit = this.requestData.limit == null ? null : this.requestData.limit * 1 || 10;
const skip = limit * (page - 1);
if (limit != null) {
if (page == null) {
this.query.limit(limit);
} else {
this.query.skip(skip).limit(limit);
}
}
return this;
}
populate() {
this.query.populate("reviews");
return this;
}
}