paginator.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. module.exports = (knex) => {
  2. return async (query, options) => {
  3. const perPage = options.perPage || 10;
  4. let page = options.page || 1;
  5. const countQuery = knex.count('* as total').from(query.clone().as('inner'));
  6. if (page < 1) {
  7. page = 1;
  8. }
  9. const offset = (page - 1) * perPage;
  10. query.offset(offset);
  11. if (perPage > 0) {
  12. query.limit(perPage);
  13. }
  14. const [data, countRows] = await Promise.all([
  15. query,
  16. countQuery
  17. ]);
  18. const total = countRows[0].total;
  19. return {
  20. pagination: {
  21. total: total,
  22. perPage,
  23. currentPage: page,
  24. lastPage: Math.ceil(total / perPage),
  25. from: offset,
  26. to: offset + data.length,
  27. },
  28. data: data
  29. };
  30. };
  31. };
  32. /*
  33. Usage:
  34. const paginator = require('./knex-paginator.js');
  35. const ticketsQuery = knex('tickets').select('*').orderBy('created_at', 'ASC');
  36. paginator(knex)(ticketsQuery, {
  37. perPage: 1,
  38. }).then(({ data, pagination }) => {
  39. console.log(data, pagination);
  40. }).catch(err => {
  41. console.log(err);
  42. });
  43. */