deepRequired.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. module.exports = function defFunc(ajv) {
  3. defFunc.definition = {
  4. type: 'object',
  5. inline: function (it, keyword, schema) {
  6. var expr = '';
  7. for (var i=0; i<schema.length; i++) {
  8. if (i) expr += ' && ';
  9. expr += '(' + getData(schema[i], it.dataLevel) + ' !== undefined)';
  10. }
  11. return expr;
  12. },
  13. metaSchema: {
  14. type: 'array',
  15. items: {
  16. type: 'string',
  17. format: 'json-pointer'
  18. }
  19. }
  20. };
  21. ajv.addKeyword('deepRequired', defFunc.definition);
  22. return ajv;
  23. };
  24. function getData(jsonPointer, lvl) {
  25. var data = 'data' + (lvl || '');
  26. if (!jsonPointer) return data;
  27. var expr = data;
  28. var segments = jsonPointer.split('/');
  29. for (var i=1; i<segments.length; i++) {
  30. var segment = segments[i];
  31. data += getProperty(unescapeJsonPointer(segment));
  32. expr += ' && ' + data;
  33. }
  34. return expr;
  35. }
  36. var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
  37. var INTEGER = /^[0-9]+$/;
  38. var SINGLE_QUOTE = /'|\\/g;
  39. function getProperty(key) {
  40. return INTEGER.test(key)
  41. ? '[' + key + ']'
  42. : IDENTIFIER.test(key)
  43. ? '.' + key
  44. : "['" + key.replace(SINGLE_QUOTE, '\\$&') + "']";
  45. }
  46. function unescapeJsonPointer(str) {
  47. return str.replace(/~1/g, '/').replace(/~0/g, '~');
  48. }