Path: blob/master/node_modules/ajv/lib/compile/async.js
1126 views
'use strict';12var MissingRefError = require('./error_classes').MissingRef;34module.exports = compileAsync;567/**8* Creates validating function for passed schema with asynchronous loading of missing schemas.9* `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.10* @this Ajv11* @param {Object} schema schema object12* @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped13* @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.14* @return {Promise} promise that resolves with a validating function.15*/16function compileAsync(schema, meta, callback) {17/* eslint no-shadow: 0 */18/* global Promise */19/* jshint validthis: true */20var self = this;21if (typeof this._opts.loadSchema != 'function')22throw new Error('options.loadSchema should be a function');2324if (typeof meta == 'function') {25callback = meta;26meta = undefined;27}2829var p = loadMetaSchemaOf(schema).then(function () {30var schemaObj = self._addSchema(schema, undefined, meta);31return schemaObj.validate || _compileAsync(schemaObj);32});3334if (callback) {35p.then(36function(v) { callback(null, v); },37callback38);39}4041return p;424344function loadMetaSchemaOf(sch) {45var $schema = sch.$schema;46return $schema && !self.getSchema($schema)47? compileAsync.call(self, { $ref: $schema }, true)48: Promise.resolve();49}505152function _compileAsync(schemaObj) {53try { return self._compile(schemaObj); }54catch(e) {55if (e instanceof MissingRefError) return loadMissingSchema(e);56throw e;57}585960function loadMissingSchema(e) {61var ref = e.missingSchema;62if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');6364var schemaPromise = self._loadingSchemas[ref];65if (!schemaPromise) {66schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);67schemaPromise.then(removePromise, removePromise);68}6970return schemaPromise.then(function (sch) {71if (!added(ref)) {72return loadMetaSchemaOf(sch).then(function () {73if (!added(ref)) self.addSchema(sch, ref, undefined, meta);74});75}76}).then(function() {77return _compileAsync(schemaObj);78});7980function removePromise() {81delete self._loadingSchemas[ref];82}8384function added(ref) {85return self._refs[ref] || self._schemas[ref];86}87}88}89}909192