-
-
Save zpao/51016aed7852f00ff478 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Instead of creating a new validator for each request, just make one and reuse it. | |
const validator = new OptionsValidator({ | |
url: { | |
//XXXzpao should probably verify that url is a valid url as well | |
is: ["string"] | |
}, | |
onComplete: { | |
is: ["function"], | |
msg: "onComplete is required and must be a function" | |
}, | |
headers: { | |
map: function (v) v || {}, | |
is: ["object"], | |
msg: "headers must be an object" | |
}, | |
content: { | |
map: function (v) v || null, | |
is: ["string", "object", "null"], | |
msg: "content must be a string or an object" | |
}, | |
contentType: { | |
map: function (v) v || "application/x-www-form-urlencoded", | |
is: ["string"] | |
} | |
}); | |
const REUSE_ERROR = "This request object has been used already. You must " + | |
"create a new one to make a new request." | |
exports.Request = apiUtils.publicConstructor(Request); | |
function Request(options) { | |
const self = this; | |
// request will hold the actual XHR object | |
let request; | |
let response; | |
options = validator.validateOptions(options); | |
// .............. | |
// Map these setters/getters to the options | |
["url", "headers", "onComplete", "content", "contentType"].forEach(function (k) { | |
this.__defineGetter__(k, function () options[k]); | |
this.__defineSetter__(k, function (v) { | |
// This will automatically rethrow errors from apiUtils.validateOptions. | |
return options[k] = validator.validateSingleOption(k, v); | |
}); | |
}, this); | |
// .............. | |
// apiUtils.validateOptions doesn't give the ability to easily validate single | |
// options, so this is a wrapper that provides that ability. | |
function OptionsValidator(rules) { | |
this.rules = rules; | |
this.validateOptions = function (options) { | |
return apiUtils.validateOptions(options, this.rules); | |
} | |
this.validateSingleOption = function (field, value) { | |
// We need to create a single rule object from our listed rules. To avoid | |
// JavaScript String warnings, check for the field & default to an empty object. | |
let singleRule = {}; | |
if (field in this.rules) { | |
singleRule[field] = this.rules[field]; | |
} | |
let singleOption = {}; | |
singleOption[field] = value; | |
// This should throw if it's invalid, which will bubble up & out. | |
return apiUtils.validateOptions(singleOption, singleRule)[field]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment