You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
2.6 KiB

  1. 'use strict';
  2. var MissingRefError = require('./error_classes').MissingRef;
  3. module.exports = compileAsync;
  4. /**
  5. * Creates validating function for passed schema with asynchronous loading of missing schemas.
  6. * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
  7. * @this Ajv
  8. * @param {Object} schema schema object
  9. * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped
  10. * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.
  11. * @return {Promise} promise that resolves with a validating function.
  12. */
  13. function compileAsync(schema, meta, callback) {
  14. /* eslint no-shadow: 0 */
  15. /* global Promise */
  16. /* jshint validthis: true */
  17. var self = this;
  18. if (typeof this._opts.loadSchema != 'function')
  19. throw new Error('options.loadSchema should be a function');
  20. if (typeof meta == 'function') {
  21. callback = meta;
  22. meta = undefined;
  23. }
  24. var p = loadMetaSchemaOf(schema).then(function () {
  25. var schemaObj = self._addSchema(schema, undefined, meta);
  26. return schemaObj.validate || _compileAsync(schemaObj);
  27. });
  28. if (callback) {
  29. p.then(
  30. function(v) { callback(null, v); },
  31. callback
  32. );
  33. }
  34. return p;
  35. function loadMetaSchemaOf(sch) {
  36. var $schema = sch.$schema;
  37. return $schema && !self.getSchema($schema)
  38. ? compileAsync.call(self, { $ref: $schema }, true)
  39. : Promise.resolve();
  40. }
  41. function _compileAsync(schemaObj) {
  42. try { return self._compile(schemaObj); }
  43. catch(e) {
  44. if (e instanceof MissingRefError) return loadMissingSchema(e);
  45. throw e;
  46. }
  47. function loadMissingSchema(e) {
  48. var ref = e.missingSchema;
  49. if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');
  50. var schemaPromise = self._loadingSchemas[ref];
  51. if (!schemaPromise) {
  52. schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
  53. schemaPromise.then(removePromise, removePromise);
  54. }
  55. return schemaPromise.then(function (sch) {
  56. if (!added(ref)) {
  57. return loadMetaSchemaOf(sch).then(function () {
  58. if (!added(ref)) self.addSchema(sch, ref, undefined, meta);
  59. });
  60. }
  61. }).then(function() {
  62. return _compileAsync(schemaObj);
  63. });
  64. function removePromise() {
  65. delete self._loadingSchemas[ref];
  66. }
  67. function added(ref) {
  68. return self._refs[ref] || self._schemas[ref];
  69. }
  70. }
  71. }
  72. }