apiPaginate.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. const LIMIT_DEFAULT = 50;
  2. const LIMIT_MAX = 1000;
  3. const OFFSET_DEFAULT = 0;
  4. const DEFAULT_MAX_RESULT_WINDOW = 10000;
  5. const parseIntValue = (value, defaultValue, maxLimit) => {
  6. if (!value) {
  7. return defaultValue;
  8. }
  9. const v = parseInt(value, 10);
  10. if (!maxLimit) {
  11. return v;
  12. }
  13. return v <= maxLimit ? v : maxLimit;
  14. };
  15. function ApiPaginate() {}
  16. ApiPaginate.parseOptionsForElasticSearch = (params) => {
  17. const limit = parseIntValue(params.limit, LIMIT_DEFAULT, LIMIT_MAX);
  18. const offset = parseIntValue(params.offset, OFFSET_DEFAULT);
  19. // See https://github.com/crowi/crowi/pull/293
  20. if (limit + offset > DEFAULT_MAX_RESULT_WINDOW) {
  21. throw new Error(
  22. `(limit + offset) must be less than or equal to ${DEFAULT_MAX_RESULT_WINDOW}`,
  23. );
  24. }
  25. return { limit, offset };
  26. };
  27. ApiPaginate.parseOptions = (params) => {
  28. const limit = parseIntValue(params.limit, LIMIT_DEFAULT, LIMIT_MAX);
  29. const offset = parseIntValue(params.offset, OFFSET_DEFAULT);
  30. return { limit, offset };
  31. };
  32. module.exports = ApiPaginate;