range.js 985 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. module.exports = function defFunc(ajv) {
  3. defFunc.definition = {
  4. type: 'number',
  5. macro: function (schema, parentSchema) {
  6. var min = schema[0]
  7. , max = schema[1]
  8. , exclusive = parentSchema.exclusiveRange;
  9. validateRangeSchema(min, max, exclusive);
  10. return {
  11. minimum: min,
  12. exclusiveMinimum: exclusive,
  13. maximum: max,
  14. exclusiveMaximum: exclusive
  15. };
  16. },
  17. metaSchema: {
  18. type: 'array',
  19. minItems: 2,
  20. maxItems: 2,
  21. items: { type: 'number' }
  22. }
  23. };
  24. ajv.addKeyword('range', defFunc.definition);
  25. ajv.addKeyword('exclusiveRange');
  26. return ajv;
  27. function validateRangeSchema(min, max, exclusive) {
  28. if (exclusive !== undefined && typeof exclusive != 'boolean')
  29. throw new Error('Invalid schema for exclusiveRange keyword, should be boolean');
  30. if (min > max || (exclusive && min == max))
  31. throw new Error('There are no numbers in range');
  32. }
  33. };