const.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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) {
  42. /* istanbul ignore if */
  43. if (it.async) {
  44. out += ' throw new ValidationError([' + (__err) + ']); ';
  45. } else {
  46. out += ' validate.errors = [' + (__err) + ']; return false; ';
  47. }
  48. } else {
  49. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  50. }
  51. out += ' }';
  52. if ($breakOnError) {
  53. out += ' else { ';
  54. }
  55. return out;
  56. }