select.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict';
  2. var util = require('./_util');
  3. module.exports = function defFunc(ajv) {
  4. if (!ajv._opts.$data) {
  5. console.warn('keyword select requires $data option');
  6. return ajv;
  7. }
  8. var metaSchemaRef = util.metaSchemaRef(ajv);
  9. var compiledCaseSchemas = [];
  10. defFunc.definition = {
  11. validate: function v(schema, data, parentSchema) {
  12. if (parentSchema.selectCases === undefined)
  13. throw new Error('keyword "selectCases" is absent');
  14. var compiled = getCompiledSchemas(parentSchema, false);
  15. var validate = compiled.cases[schema];
  16. if (validate === undefined) validate = compiled.default;
  17. if (typeof validate == 'boolean') return validate;
  18. var valid = validate(data);
  19. if (!valid) v.errors = validate.errors;
  20. return valid;
  21. },
  22. $data: true,
  23. metaSchema: { type: ['string', 'number', 'boolean', 'null'] }
  24. };
  25. ajv.addKeyword('select', defFunc.definition);
  26. ajv.addKeyword('selectCases', {
  27. compile: function (schemas, parentSchema) {
  28. var compiled = getCompiledSchemas(parentSchema);
  29. for (var value in schemas)
  30. compiled.cases[value] = compileOrBoolean(schemas[value]);
  31. return function() { return true; };
  32. },
  33. valid: true,
  34. metaSchema: {
  35. type: 'object',
  36. additionalProperties: metaSchemaRef
  37. }
  38. });
  39. ajv.addKeyword('selectDefault', {
  40. compile: function (schema, parentSchema) {
  41. var compiled = getCompiledSchemas(parentSchema);
  42. compiled.default = compileOrBoolean(schema);
  43. return function() { return true; };
  44. },
  45. valid: true,
  46. metaSchema: metaSchemaRef
  47. });
  48. return ajv;
  49. function getCompiledSchemas(parentSchema, create) {
  50. var compiled;
  51. compiledCaseSchemas.some(function (c) {
  52. if (c.parentSchema === parentSchema) {
  53. compiled = c;
  54. return true;
  55. }
  56. });
  57. if (!compiled && create !== false) {
  58. compiled = {
  59. parentSchema: parentSchema,
  60. cases: {},
  61. default: true
  62. };
  63. compiledCaseSchemas.push(compiled);
  64. }
  65. return compiled;
  66. }
  67. function compileOrBoolean(schema) {
  68. return typeof schema == 'boolean'
  69. ? schema
  70. : ajv.compile(schema);
  71. }
  72. };