apiPaginate.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 = function(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 = function(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(`(limit + offset) must be less than or equal to ${DEFAULT_MAX_RESULT_WINDOW}`);
  22. }
  23. return { limit, offset };
  24. };
  25. ApiPaginate.parseOptions = function(params) {
  26. const limit = parseIntValue(params.limit, LIMIT_DEFAULT, LIMIT_MAX);
  27. const offset = parseIntValue(params.offset, OFFSET_DEFAULT);
  28. return { limit, offset };
  29. };
  30. module.exports = ApiPaginate;