-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathpaginate.js
64 lines (52 loc) · 1.38 KB
/
paginate.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
58
59
60
61
62
63
64
/**
====================================
Readme Sequelize Paginate Helper
====================================
## Usage
// require your model model
const { YOUR-MODEL } = require("<SEQUELIZE MODEL PATH>")
// require the paginate helper
const paginate = require("<PATH TO PAGINATE HELPER>")
// destruct the params
let { page, limit, search } = params
// import the paginate helper
const data = await paginate("<YOUR-MODEL>", page, limit, search)
// see the result
console.log(data.data, ">>>>>> result")
*/
module.exports = async (model, pageQuery, limitQuery, searchQuery) => {
const page = parseInt(pageQuery) || 1;
const limit = parseInt(limitQuery) || 10;
const startIndex = (page - 1) * limit;
const endIndex = page * limit;
const results = {
data: [],
meta: {},
};
const total = await model.count();
const totalPages = Math.ceil(total / limit);
if (endIndex < total) {
results.meta.next = page + 1;
} else {
results.meta.next = null;
}
if (startIndex > 0) {
results.meta.previous = page - 1;
} else {
results.meta.previous = null;
}
results.meta.page = page;
results.meta.total = total;
results.meta.limit = limit;
results.meta.totalPages = totalPages;
try {
results.data = await model.findAll({
offset: startIndex,
limit: limit,
where: searchQuery,
})
return results;
} catch (e) {
return e;
}
}