Skip to content

Instantly share code, notes, and snippets.

@jhthorsen
Created October 10, 2015 13:05
Show Gist options
  • Save jhthorsen/e0c75c42eb4b4bc1abaf to your computer and use it in GitHub Desktop.
Save jhthorsen/e0c75c42eb4b4bc1abaf to your computer and use it in GitHub Desktop.
(function() {
/*
var swagger = new SwaggerClient({swagger: "2.0", info: {}, paths: {}});
swagger.listPets({limit: 10}, function(err, xhr) {
console.log(xhr.code, xhr.body);
});
*/
window.SwaggerClient = function(spec) {
var self = this;
this.baseUrl = (spec.baseUrl || '').replace(/\//, '');
// Generate methods from spec
Object.keys(spec.paths).forEach(function(path) {
Object.keys(spec.paths[path]).forEach(function(httpMethod) {
var opSpec = spec.paths[path][httpMethod];
var pathList = path.split('/');
self[opSpec.operationId] = function(args, cb) {
var req, xhr = new XMLHttpRequest();
xhr.url = pathList;
req = this.makeRequest(args, opSpec.parameters || [], xhr);
xhr.open(httpMethod, req.url);
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
xhr.body = xhr.responseText.match(/^[\{\[]/) ? JSON.parse(xhr.responseText) : xhr.responseText;
cb.call(this, xhr.status == 200 ? null : {}, xhr);
}.bind(this);
xhr.send(req.body);
};
}
});
};
var proto = window.SwaggerClient.prototype;
proto.makeRequest = function(args, parameters, xhr) {
var form = [], json = {}, query = [], str;
var req = {body: null};
var url = [this.baseUrl];
xhr.url.forEach(function(p) {
url.push(p.replace(/\{(\w+)\}/, function(m, n) { return args[n]; }));
});
for (i = 0; i < parameters.length; i++) {
var p = parameters[i];
var name = p.name;
var value = args[name];
if (typeof value == 'undefined') value = p['default'];
if (typeof value == 'undefined') continue;
switch (p['in']) {
case 'query':
query.push([name, value]);
break;
case 'file':
req.body = value;
break;
case 'body':
json[name] = value;
break;
case 'header':
xhr.setRequestHeader(name, value);
break;
case 'formData':
form.push([name, value]);
break;
}
}
if (Object.keys(req.json).length) {
xhr.setRequestHeader('Content-Type', 'application/json');
req.body = JSON.stringify(req.json);
}
else if(form.length) {
str = [];
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
form.forEach(function(i) { str.push(encodeURIComponent(i[0]) + '=' + encodeURIComponent(i[1])); });
req.body = str.join('&');
}
if (query.length) {
str = [];
query.forEach(function(i) { str.push(encodeURIComponent(i[0]) + '=' + encodeURIComponent(i[1])); });
req.url += '?' + str.join('&');
}
xhr.url = url.join('/');
return req;
};
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment