pagination.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import _ from "lodash";
  2. export default (default_sort, default_offset, default_limit, max_limit) => {
  3. /**
  4. * This will setup the req query params with filtered data and defaults
  5. *
  6. * sort will be an array of fields and their direction
  7. * offset will be an int, defaulting to zero if no other default supplied
  8. * limit will be an int, defaulting to 50 if no other default supplied, and limited to the max if that was supplied
  9. *
  10. */
  11. return (req, _res, next) => {
  12. req.query.offset =
  13. typeof req.query.limit === "undefined" ? default_offset || 0 : Number.parseInt(req.query.offset, 10);
  14. req.query.limit =
  15. typeof req.query.limit === "undefined" ? default_limit || 50 : Number.parseInt(req.query.limit, 10);
  16. if (max_limit && req.query.limit > max_limit) {
  17. req.query.limit = max_limit;
  18. }
  19. // Sorting
  20. let sort = typeof req.query.sort === "undefined" ? default_sort : req.query.sort;
  21. const myRegexp = /.*\.(asc|desc)$/gi;
  22. const sort_array = [];
  23. sort = sort.split(",");
  24. _.map(sort, (val) => {
  25. const matches = myRegexp.exec(val);
  26. if (matches !== null) {
  27. const dir = matches[1];
  28. sort_array.push({
  29. field: val.substr(0, val.length - (dir.length + 1)),
  30. dir: dir.toLowerCase(),
  31. });
  32. } else {
  33. sort_array.push({
  34. field: val,
  35. dir: "asc",
  36. });
  37. }
  38. });
  39. // Sort will now be in this format:
  40. // [
  41. // { field: 'field1', dir: 'asc' },
  42. // { field: 'field2', dir: 'desc' }
  43. // ]
  44. req.query.sort = sort_array;
  45. next();
  46. };
  47. };