const.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. module.exports = function generate_const(it, $keyword, $ruleType) {
  3. var out = ' ';
  4. var $lvl = it.level;
  5. var $dataLvl = it.dataLevel;
  6. var $schema = it.schema[$keyword];
  7. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  8. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  9. var $breakOnError = !it.opts.allErrors;
  10. var $data = 'data' + ($dataLvl || '');
  11. var $valid = 'valid' + $lvl;
  12. var $isData = it.opts.$data && $schema && $schema.$data,
  13. $schemaValue;
  14. if ($isData) {
  15. out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
  16. $schemaValue = 'schema' + $lvl;
  17. } else {
  18. $schemaValue = $schema;
  19. }
  20. if (!$isData) {
  21. out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';';
  22. }
  23. out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { ';
  24. var $$outStack = $$outStack || [];
  25. $$outStack.push(out);
  26. out = ''; /* istanbul ignore else */
  27. if (it.createErrors !== false) {
  28. out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } ';
  29. if (it.opts.messages !== false) {
  30. out += ' , message: \'should be equal to constant\' ';
  31. }
  32. if (it.opts.verbose) {
  33. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  34. }
  35. out += ' } ';
  36. } else {
  37. out += ' {} ';
  38. }
  39. var __err = out;
  40. out = $$outStack.pop();
  41. if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
  42. if (it.async) {
  43. out += ' throw new ValidationError([' + (__err) + ']); ';
  44. } else {
  45. out += ' validate.errors = [' + (__err) + ']; return false; ';
  46. }
  47. } else {
  48. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  49. }
  50. out += ' }';
  51. if ($breakOnError) {
  52. out += ' else { ';
  53. }
  54. return out;
  55. }