1class APIFeatures {
2 /**
3 *
4 * @param {mongoose model} query
5 * @param {req.query} queryString
6 */
7 constructor(query, queryString) {
8 this.query = query;
9 this.queryString = queryString;
10 }
11
12 filter() {
13 const queryObj = { ...this.queryString };
14 const excludeFields = ['page', 'sort', 'limit', 'fields'];
15 excludeFields.forEach((el) => {
16 delete queryObj[el];
17 });
18
19 //* Advanced filtering *\\
20 let queryStr = JSON.stringify(queryObj);
21 queryStr = queryStr.replace(
22 /\b(gte|gt|lte|lt)\b/g,
23 (match) => `$${match}`,
24 );
25 this.query.find(JSON.parse(queryStr));
26 return this;
27 }
28
29 sort() {
30 if (this.queryString.sort) {
31 const sortBy = this.queryString.sort.split(',').join(' ');
32 this.query = this.query.sort(sortBy);
33 } else {
34 this.query = this.query.sort('-createdAt');
35 }
36 return this;
37 }
38
39 limitFields() {
40 if (this.queryString.fields) {
41 const fields = this.queryString.fields.split(',').join(' ');
42 this.query = this.query.select(fields);
43 } else {
44 this.query = this.query.select('-__v');
45 }
46 return this;
47 }
48
49 paginate() {
50 const page = this.queryString.page * 1 || 1;
51 const limit = this.queryString.limit * 1 || 100;
52 const skip = (page - 1) * limit;
53
54 this.query = this.query.skip(skip).limit(limit);
55 return this;
56 }
57}
Backlinks