Skip to content

Commit 2f62264

Browse files
committed
utils: api feature + app error + catch async errors
1 parent 62ca505 commit 2f62264

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed

utils/api_feature.js

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
export class ApiFeatures {
2+
constructor(mongooseQuery, queryString) {
3+
this.mongooseQuery = mongooseQuery;
4+
this.queryString = queryString;
5+
}
6+
7+
pagination() {
8+
const PAGE_LIMIT = 3;
9+
let PAGE_NUMBER = this.queryString.page * 1 || 1;
10+
if (this.queryString.page <= 0) PAGE_NUMBER = 1;
11+
const PAGE_SKIP = (PAGE_NUMBER - 1) * PAGE_LIMIT;
12+
13+
this.mongooseQuery.skip(PAGE_SKIP).limit(PAGE_LIMIT);
14+
return this;
15+
}
16+
17+
filteration() {
18+
let filterObj = { ...this.queryString };
19+
20+
let excludedQuery = ["page", "sort", "fields", "keyword"];
21+
22+
excludedQuery.forEach((ele) => {
23+
delete filterObj[ele];
24+
});
25+
filterObj = JSON.stringify(filterObj);
26+
27+
filterObj = filterObj.replace(
28+
/\b(gt|gte|lt|lte)\b/g,
29+
(match) => `$${match}`
30+
);
31+
filterObj = JSON.parse(filterObj);
32+
33+
this.mongooseQuery.find(filterObj);
34+
return this;
35+
}
36+
37+
sort() {
38+
if (this.queryString.sort) {
39+
let sortedBy = this.queryString.sort.split(",").join(" ");
40+
this.mongooseQuery.sort(sortedBy);
41+
}
42+
return this;
43+
}
44+
45+
search() {
46+
if (this.queryString.keyword) {
47+
48+
this.mongooseQuery.find({
49+
$or: [
50+
{ title: { $regex: this.queryString.keyword, $options: "i" } },
51+
{ descripton: { $regex: this.queryString.keyword, $options: "i" } },
52+
],
53+
});
54+
}
55+
return this;
56+
}
57+
58+
59+
fields() {
60+
if (this.queryString.fields) {
61+
let fields = this.queryString.fields.split(",").join(" ");
62+
console.log(fields);
63+
}
64+
return this;
65+
}
66+
}

utils/app_error.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export class AppError extends Error {
2+
constructor(message, statuscode) {
3+
super(message);
4+
this.statuscode = statuscode;
5+
}
6+
}

utils/catch_async_error.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export let catchAsyncError = (fn) => {
2+
return (req, res, next) => {
3+
fn(req, res, next).catch((err) => next(err));
4+
};
5+
};

0 commit comments

Comments
 (0)