-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
57 lines (45 loc) · 1.45 KB
/
middleware.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
exports.advanceQuerying = (model) => async (req, res, next) => {
try {
let query
const reqQuery = { ...req.query }
const removeFields = ["select", "page", "limit"]
removeFields.forEach((param) => delete reqQuery[param])
let queryStr = JSON.stringify(reqQuery)
query = model.find(JSON.parse(queryStr))
if (req.query.select) {
const fields = req.query.select.split(",").join(" ")
query = query.select(fields)
}
const page = parseInt(req.query.page, 10) || 1
const limit = parseInt(req.query.limit, 10) || 10
const startIndex = (page - 1) * limit
const endIndex = page * limit
const total = await model.countDocuments()
query = query.skip(startIndex).limit(limit)
const results = await query
const pagination = {}
if (endIndex < total) {
pagination.next = {
page: page + 1,
limit,
}
}
if (startIndex > 0) {
pagination.prev = {
page: page - 1,
limit,
}
}
res.advanceQuerying = {
status: true,
count: results.count,
pagination,
data: results,
}
next()
} catch (error) {
res.status(500).json({
error: "Unknown query parameter or maybe the server is dowm...",
})
}
}