Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tv4.async vanilla implementation #224

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions tv4.async-vanilla.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Provides support for asynchronous validation (fetching schemas)
// Callback is optional third argument to tv4.validate() - if not present, synchronous operation
// callback(result, error);
if (typeof tv4.asyncValidate === 'undefined') {
tv4.syncValidate = tv4.validate;
tv4.validate = function (data, schema, callback, checkRecursive, banUnknownProperties) {
if (typeof callback === 'undefined')
return this.syncValidate(data, schema, checkRecursive, banUnknownProperties);
else
return this.asyncValidate(data, schema, callback, checkRecursive, banUnknownProperties);
};
tv4.asyncValidate = function (data, schema, callback, checkRecursive, banUnknownProperties) {
var result = tv4.validate(data, schema, checkRecursive, banUnknownProperties);
if (!tv4.missing.length)
return callback(result, tv4.error);

// Make a request for each missing schema
var missingSchemas = function() {
tv4.missing.map(function (schemaUri) {
var request = new XMLHttpRequest();
request.open('GET', schemaUri, true);

request.onload = function() {
if (request.status >= 200 && request.status < 400)
tv4.addSchema(schemaUri, JSON.parse(request.responseText));
else {
// If there's an error, just use an empty schema
tv4.addSchema(schemaUri, {});
}
};

request.onerror = function() {
tv4.addSchema(schemaUri, {});
};

request.send();
})
};
// When all requests done, try again
//missingSchemas();
$.when.apply($, missingSchemas).done(function () {
var result = tv4.asyncValidate(data, schema, callback, checkRecursive, banUnknownProperties);
});
};
}