3 var MissingRefError = require('./error_classes').MissingRef;
5 module.exports = compileAsync;
9 * Creates validating function for passed schema with asynchronous loading of missing schemas.
10 * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
12 * @param {Object} schema schema object
13 * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped
14 * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.
15 * @return {Promise} promise that resolves with a validating function.
17 function compileAsync(schema, meta, callback) {
18 /* eslint no-shadow: 0 */
20 /* jshint validthis: true */
22 if (typeof this._opts.loadSchema != 'function')
23 throw new Error('options.loadSchema should be a function');
25 if (typeof meta == 'function') {
30 var p = loadMetaSchemaOf(schema).then(function () {
31 var schemaObj = self._addSchema(schema, undefined, meta);
32 return schemaObj.validate || _compileAsync(schemaObj);
37 function(v) { callback(null, v); },
45 function loadMetaSchemaOf(sch) {
46 var $schema = sch.$schema;
47 return $schema && !self.getSchema($schema)
48 ? compileAsync.call(self, { $ref: $schema }, true)
53 function _compileAsync(schemaObj) {
54 try { return self._compile(schemaObj); }
56 if (e instanceof MissingRefError) return loadMissingSchema(e);
61 function loadMissingSchema(e) {
62 var ref = e.missingSchema;
63 if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');
65 var schemaPromise = self._loadingSchemas[ref];
67 schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
68 schemaPromise.then(removePromise, removePromise);
71 return schemaPromise.then(function (sch) {
73 return loadMetaSchemaOf(sch).then(function () {
74 if (!added(ref)) self.addSchema(sch, ref, undefined, meta);
78 return _compileAsync(schemaObj);
81 function removePromise() {
82 delete self._loadingSchemas[ref];
86 return self._refs[ref] || self._schemas[ref];