forked from Laboratoria/BOG003-burger-queen-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpagination.js
38 lines (37 loc) · 956 Bytes
/
pagination.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
const convertLinks = require('./links');
const pagination = async (req, res, model, path) => {
const { page = Number(1), limit = Number(10) } = req.query;
const { host } = req.headers;
await model.find();
try {
const posts = await model.find()
.limit(limit * 1)
.skip((page - 1) * limit)
.exec();
const count = await model.countDocuments();
const results = {
posts,
totalDocuments: count,
totalPages: Math.ceil(count / limit),
currentPage: page,
};
if (page - 1 > 0) {
results.previous = {
page: page - 1,
limit,
};
}
if (page * limit < count) {
results.next = {
page: page + 1,
limit,
};
}
const link = convertLinks(host, path, limit, page, results.totalPages);
res.set('Link', JSON.stringify(link));
res.json(results);
} catch (err) {
console.log(err.message);
}
};
module.exports = pagination;