File size: 1,882 Bytes
97f53b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
export class ApiFeatures {
  constructor(mongooseQuery, queryString) {
    this.mongooseQuery = mongooseQuery;
    this.queryString = queryString;
  }

  //1-Pagination
  pagination() {
    const PAGE_LIMIT = 3;
    let PAGE_NUMBER = this.queryString.page * 1 || 1;
    if (this.queryString.page <= 0) PAGE_NUMBER = 1;
    const PAGE_SKIP = (PAGE_NUMBER - 1) * PAGE_LIMIT; //2*3

    this.mongooseQuery.skip(PAGE_SKIP).limit(PAGE_LIMIT);
    return this;
  }

  //2-Filteration

  filteration() {
    let filterObj = { ...this.queryString };
    // console.log(filterObj);

    let excludedQuery = ["page", "sort", "fields", "keyword"];

    excludedQuery.forEach((ele) => {
      delete filterObj[ele];
    });
    filterObj = JSON.stringify(filterObj);
    // console.log(filterObj);

    filterObj = filterObj.replace(
      /\b(gt|gte|lt|lte)\b/g,
      (match) => `$${match}`
    );
    filterObj = JSON.parse(filterObj);

    this.mongooseQuery.find(filterObj);
    return this;
  }
  //3-Sort
  sort() {
    if (this.queryString.sort) {
      // console.log(req.query.sort);
      let sortedBy = this.queryString.sort.split(",").join(" ");
      // console.log(sortedBy);
      this.mongooseQuery.sort(sortedBy);
    }
    return this;
  }
  //4-Search

  search() {
    if (this.queryString.keyword) {
      // console.log(this.queryString.keyword);

      this.mongooseQuery.find({
        $or: [
          { title: { $regex: this.queryString.keyword, $options: "i" } },
          { descripton: { $regex: this.queryString.keyword, $options: "i" } },
        ],
      });
    }
    return this;
  }

  //4-Fields

  fields() {
    if (this.queryString.fields) {
      // console.log(this.queryString.fields);
      let fields = this.queryString.fields.split(",").join(" ");
      console.log(fields);
      // this.mongooseQuery.select(fields);
    }
    return this;
  }
}