3 * swagger-client - swagger.js is a javascript client for use with swaggering APIs.
5 * @link http://swagger.io
9 var ArrayModel = function(definition) {
10 this.name = "arrayModel";
11 this.definition = definition || {};
14 var requiredFields = definition.enum || [];
15 var innerType = definition.items;
18 this.type = typeFromJsonSchema(innerType.type, innerType.format);
21 this.ref = innerType.$ref;
27 ArrayModel.prototype.createJSONSample = function(modelsToIgnore) {
29 modelsToIgnore = (modelsToIgnore||{});
34 var name = simpleRef(this.ref);
35 if(typeof modelsToIgnore[name] === 'undefined') {
36 modelsToIgnore[name] = this;
37 result = models[name].createJSONSample(modelsToIgnore);
46 ArrayModel.prototype.getSampleValue = function(modelsToIgnore) {
48 modelsToIgnore = (modelsToIgnore || {});
53 var name = simpleRef(this.ref);
54 result = models[name].getSampleValue(modelsToIgnore);
59 ArrayModel.prototype.getMockSignature = function(modelsToIgnore) {
60 var propertiesStr = [];
62 for (i = 0; i < this.properties.length; i++) {
63 prop = this.properties[i];
64 propertiesStr.push(prop.toString());
67 var strong = '<span class="strong">';
68 var stronger = '<span class="stronger">';
69 var strongClose = '</span>';
70 var classOpen = strong + 'array' + ' {' + strongClose;
71 var classClose = strong + '}' + strongClose;
72 var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
76 modelsToIgnore[this.name] = this;
77 for (i = 0; i < this.properties.length; i++) {
78 prop = this.properties[i];
80 var model = models[ref];
81 if (model && typeof modelsToIgnore[ref] === 'undefined') {
82 returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
90 * SwaggerAuthorizations applys the correct authorization to an operation being executed
92 var SwaggerAuthorizations = function() {
96 SwaggerAuthorizations.prototype.add = function(name, auth) {
97 this.authz[name] = auth;
101 SwaggerAuthorizations.prototype.remove = function(name) {
102 return delete this.authz[name];
105 SwaggerAuthorizations.prototype.apply = function (obj, authorizations) {
107 var key, name, value, result;
109 // if the "authorizations" key is undefined, or has an empty array, add all keys
110 if (typeof authorizations === 'undefined' || Object.keys(authorizations).length === 0) {
111 for (key in this.authz) {
112 value = this.authz[key];
113 result = value.apply(obj, authorizations);
120 if (Array.isArray(authorizations)) {
122 for (var i = 0; i < authorizations.length; i++) {
123 var auth = authorizations[i];
125 for (key in this.authz) {
127 value = this.authz[key];
128 result = value.apply(obj, authorizations);
138 for (name in authorizations) {
139 for (key in this.authz) {
141 value = this.authz[key];
142 result = value.apply(obj, authorizations);
155 * ApiKeyAuthorization allows a query param or header to be injected
157 var ApiKeyAuthorization = function(name, value, type) {
163 ApiKeyAuthorization.prototype.apply = function(obj, authorizations) {
164 if (this.type === "query") {
165 if (obj.url.indexOf('?') > 0)
166 obj.url = obj.url + "&" + this.name + "=" + this.value;
168 obj.url = obj.url + "?" + this.name + "=" + this.value;
170 } else if (this.type === "header") {
171 obj.headers[this.name] = this.value;
176 var CookieAuthorization = function(cookie) {
177 this.cookie = cookie;
180 CookieAuthorization.prototype.apply = function(obj, authorizations) {
181 obj.cookieJar = obj.cookieJar || CookieJar();
182 obj.cookieJar.setCookie(this.cookie);
187 * Password Authorization is a basic auth implementation
189 var PasswordAuthorization = function(name, username, password) {
191 this.username = username;
192 this.password = password;
194 if (typeof window !== 'undefined')
197 this._btoa = require("btoa");
200 PasswordAuthorization.prototype.apply = function(obj, authorizations) {
201 var base64encoder = this._btoa;
202 obj.headers.Authorization = "Basic " + base64encoder(this.username + ":" + this.password);
205 var __bind = function(fn, me){
207 return fn.apply(me, arguments);
211 fail = function(message) {
216 log.history = log.history || [];
217 log.history.push(arguments);
219 console.log( Array.prototype.slice.call(arguments)[0] );
223 if (!Array.prototype.indexOf) {
224 Array.prototype.indexOf = function(obj, start) {
225 for (var i = (start || 0), j = this.length; i < j; i++) {
226 if (this[i] === obj) { return i; }
233 * allows override of the default value based on the parameter being
236 var applyParameterMacro = function (operation, parameter) {
237 var e = (typeof window !== 'undefined' ? window : exports);
239 return e.parameterMacro(operation, parameter);
241 return parameter.defaultValue;
245 * allows overriding the default value of an model property
247 var applyModelPropertyMacro = function (model, property) {
248 var e = (typeof window !== 'undefined' ? window : exports);
249 if(e.modelPropertyMacro)
250 return e.modelPropertyMacro(model, property);
252 return property.defaultValue;
258 var PrimitiveModel = function(definition) {
260 this.definition = definition || {};
261 this.properties = [];
263 var requiredFields = definition.enum || [];
264 this.type = typeFromJsonSchema(definition.type, definition.format);
267 PrimitiveModel.prototype.createJSONSample = function(modelsToIgnore) {
268 var result = this.type;
272 PrimitiveModel.prototype.getSampleValue = function() {
273 var result = this.type;
277 PrimitiveModel.prototype.getMockSignature = function(modelsToIgnore) {
278 var propertiesStr = [];
280 for (i = 0; i < this.properties.length; i++) {
281 prop = this.properties[i];
282 propertiesStr.push(prop.toString());
285 var strong = '<span class="strong">';
286 var stronger = '<span class="stronger">';
287 var strongClose = '</span>';
288 var classOpen = strong + this.name + ' {' + strongClose;
289 var classClose = strong + '}' + strongClose;
290 var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
294 modelsToIgnore[this.name] = this;
295 for (i = 0; i < this.properties.length; i++) {
296 prop = this.properties[i];
298 var model = models[ref];
299 if (model && typeof modelsToIgnore[ref] === 'undefined') {
300 returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
306 * Resolves a spec's remote references
308 var Resolver = function (){};
310 Resolver.prototype.resolve = function(spec, callback, scope) {
311 this.scope = (scope || this);
312 var host, name, path, property, propertyName, type;
313 var processedCalls = 0, resolvedRefs = {}, unresolvedRefs = {};
315 // store objects for dereferencing
316 var resolutionTable = {};
319 for(name in spec.definitions) {
320 var model = spec.definitions[name];
321 for(propertyName in model.properties) {
322 property = model.properties[propertyName];
323 this.resolveTo(property, resolutionTable);
327 for(name in spec.paths) {
328 var method, operation, responseCode;
329 path = spec.paths[name];
330 for(method in path) {
331 operation = path[method];
332 var i, parameters = operation.parameters;
333 for(i in parameters) {
334 var parameter = parameters[i];
335 if(parameter.in === 'body' && parameter.schema) {
336 this.resolveTo(parameter.schema, resolutionTable);
339 this.resolveInline(spec, parameter, resolutionTable, unresolvedRefs);
342 for(responseCode in operation.responses) {
343 var response = operation.responses[responseCode];
344 if(response.schema) {
345 this.resolveTo(response.schema, resolutionTable);
351 var opts = {}, expectedCalls = 0;
352 for(name in resolutionTable) {
353 var parts = name.split('#');
354 if(parts.length == 2) {
355 host = parts[0]; path = parts[1];
356 if(!Array.isArray(opts[host])) {
360 opts[host].push(path);
365 var self = this, opt = opts[name];
369 useJQuery: false, // TODO
373 accept: this.scope.swaggerRequestHeaders || 'application/json'
376 error: function(response) {
379 for(i = 0; i < opt.length; i++) {
381 var resolved = host + '#' + opt[i];
382 unresolvedRefs[resolved] = null;
384 if(processedCalls === expectedCalls)
385 self.finish(spec, resolutionTable, resolvedRefs, unresolvedRefs, callback);
387 response: function(response) {
388 var i, j, swagger = response.obj;
390 for(i = 0; i < opt.length; i++) {
391 var location = swagger, path = opt[i], parts = path.split('/');
392 for(j = 0; j < parts.length; j++) {
393 var segment = parts[j];
394 if(typeof location === 'undefined')
396 if(segment.length > 0)
397 location = location[segment];
399 var resolved = host + '#' + path, resolvedName = parts[j-1];
400 if(typeof location !== 'undefined') {
401 resolvedRefs[resolved] = {
406 else unresolvedRefs[resolved] = null;
408 if(processedCalls === expectedCalls)
409 self.finish(spec, resolutionTable, resolvedRefs, unresolvedRefs, callback);
413 authorizations.apply(obj);
414 new SwaggerHttp().execute(obj);
416 if(Object.keys(opts).length === 0)
417 callback.call(this.scope, spec, unresolvedRefs);
420 Resolver.prototype.finish = function(spec, resolutionTable, resolvedRefs, unresolvedRefs, callback) {
421 // walk resolution table and replace with resolved refs
423 for(ref in resolutionTable) {
424 var i, locations = resolutionTable[ref];
425 for(i = 0; i < locations.length; i++) {
426 var resolvedTo = resolvedRefs[locations[i].obj.$ref];
428 if(!spec.definitions)
429 spec.definitions = {};
430 if(locations[i].resolveAs === '$ref') {
431 spec.definitions[resolvedTo.name] = resolvedTo.obj;
432 locations[i].obj.$ref = '#/definitions/' + resolvedTo.name;
434 else if (locations[i].resolveAs === 'inline') {
436 var targetObj = locations[i].obj;
437 delete targetObj.$ref;
438 for(key in resolvedTo.obj) {
439 targetObj[key] = resolvedTo.obj[key];
445 callback.call(this.scope, spec, unresolvedRefs);
449 * immediately in-lines local refs, queues remote refs
450 * for inline resolution
452 Resolver.prototype.resolveInline = function (spec, property, objs, unresolvedRefs) {
453 var ref = property.$ref;
455 if(ref.indexOf('http') === 0) {
456 if(Array.isArray(objs[ref])) {
457 objs[ref].push({obj: property, resolveAs: 'inline'});
460 objs[ref] = [{obj: property, resolveAs: 'inline'}];
463 else if (ref.indexOf('#') === 0) {
465 var shortenedRef = ref.substring(1);
466 var i, parts = shortenedRef.split('/'), location = spec;
467 for(i = 0; i < parts.length; i++) {
469 if(part.length > 0) {
470 location = location[part];
474 delete property.$ref;
476 for(key in location) {
477 property[key] = location[key];
480 else unresolvedRefs[ref] = null;
483 else if(property.type === 'array') {
484 this.resolveTo(property.items, objs);
488 Resolver.prototype.resolveTo = function (property, objs) {
489 var ref = property.$ref;
491 if(ref.indexOf('http') === 0) {
492 if(Array.isArray(objs[ref])) {
493 objs[ref].push({obj: property, resolveAs: '$ref'});
496 objs[ref] = [{obj: property, resolveAs: '$ref'}];
500 else if(property.type === 'array') {
501 var items = property.items;
502 this.resolveTo(items, objs);
505 var addModel = function(name, model) {
506 models[name] = model;
509 var SwaggerClient = function(url, options) {
510 this.isBuilt = false;
513 this.basePath = null;
514 this.modelsArray = [];
515 this.authorizations = null;
516 this.authorizationScheme = null;
517 this.isValid = false;
519 this.useJQuery = false;
520 this.resourceCount = 0;
522 if(typeof url !== 'undefined')
523 return this.initialize(url, options);
526 SwaggerClient.prototype.initialize = function (url, options) {
527 this.models = models = {};
529 options = (options||{});
531 if(typeof url === 'string')
533 else if(typeof url === 'object') {
535 this.url = options.url;
537 this.swaggerRequstHeaders = options.swaggerRequstHeaders || 'application/json;charset=utf-8,*/*';
538 this.defaultSuccessCallback = options.defaultSuccessCallback || null;
539 this.defaultErrorCallback = options.defaultErrorCallback || null;
541 if (typeof options.success === 'function')
542 this.success = options.success;
544 if (options.useJQuery)
545 this.useJQuery = options.useJQuery;
547 if (options.authorizations) {
548 this.clientAuthorizations = options.authorizations;
550 this.clientAuthorizations = authorizations;
553 this.supportedSubmitMethods = options.supportedSubmitMethods || [];
554 this.failure = options.failure || function() {};
555 this.progress = options.progress || function() {};
556 this.spec = options.spec;
557 this.options = options;
559 if (typeof options.success === 'function') {
565 SwaggerClient.prototype.build = function(mock) {
566 if (this.isBuilt) return this;
568 this.progress('fetching resource list: ' + this.url);
570 useJQuery: this.useJQuery,
574 accept: this.swaggerRequstHeaders
577 error: function(response) {
578 if (self.url.substring(0, 4) !== 'http')
579 return self.fail('Please specify the protocol for ' + self.url);
580 else if (response.status === 0)
581 return self.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.');
582 else if (response.status === 404)
583 return self.fail('Can\'t read swagger JSON from ' + self.url);
585 return self.fail(response.status + ' : ' + response.statusText + ' ' + self.url);
587 response: function(resp) {
588 var responseObj = resp.obj || JSON.parse(resp.data);
589 self.swaggerVersion = responseObj.swaggerVersion;
591 if(responseObj.swagger && parseInt(responseObj.swagger) === 2) {
592 self.swaggerVersion = responseObj.swagger;
593 new Resolver().resolve(responseObj, self.buildFromSpec, self);
597 if (self.swaggerVersion === '1.2') {
598 return self.buildFrom1_2Spec(responseObj);
600 return self.buildFrom1_1Spec(responseObj);
607 setTimeout(function() {
608 new Resolver().resolve(self.spec, self.buildFromSpec, self);
612 authorizations.apply(obj);
615 new SwaggerHttp().execute(obj);
620 SwaggerClient.prototype.buildFromSpec = function(response) {
621 if(this.isBuilt) return this;
623 this.info = response.info || {};
624 this.title = response.title || '';
625 this.host = response.host || '';
626 this.schemes = response.schemes || [];
627 this.basePath = response.basePath || '';
630 this.consumes = response.consumes;
631 this.produces = response.produces;
632 this.securityDefinitions = response.securityDefinitions;
635 this.authSchemes = response.securityDefinitions;
637 var definedTags = {};
638 if(Array.isArray(response.tags)) {
640 for(k = 0; k < response.tags.length; k++) {
641 var t = response.tags[k];
642 definedTags[t.name] = t;
647 if(typeof this.url === 'string') {
648 location = this.parseUri(this.url);
651 if(typeof this.schemes === 'undefined' || this.schemes.length === 0) {
652 this.scheme = location.scheme || 'http';
655 this.scheme = this.schemes[0];
658 if(typeof this.host === 'undefined' || this.host === '') {
659 this.host = location.host;
661 this.host = this.host + ':' + location.port;
665 this.definitions = response.definitions;
667 for(key in this.definitions) {
668 var model = new Model(key, this.definitions[key]);
674 // get paths, create functions for each operationId
677 for(path in response.paths) {
678 if(typeof response.paths[path] === 'object') {
680 for(httpMethod in response.paths[path]) {
681 if(['delete', 'get', 'head', 'options', 'patch', 'post', 'put'].indexOf(httpMethod) === -1) {
684 var operation = response.paths[path][httpMethod];
685 var tags = operation.tags;
686 if(typeof tags === 'undefined') {
687 operation.tags = [ 'default' ];
688 tags = operation.tags;
690 var operationId = this.idFromOp(path, httpMethod, operation);
691 var operationObject = new Operation (
700 // bind this operation's execute command to the api
701 if(tags.length > 0) {
703 for(i = 0; i < tags.length; i++) {
704 var tag = this.tagFromLabel(tags[i]);
705 var operationGroup = this[tag];
706 if(typeof this.apis[tag] === 'undefined')
708 if(typeof operationGroup === 'undefined') {
710 operationGroup = this[tag];
711 operationGroup.operations = {};
712 operationGroup.label = tag;
713 operationGroup.apis = [];
714 var tagObject = definedTags[tag];
715 if(typeof tagObject === 'object') {
716 operationGroup.description = tagObject.description;
717 operationGroup.externalDocs = tagObject.externalDocs;
719 this[tag].help = this.help.bind(operationGroup);
720 this.apisArray.push(new OperationGroup(tag, operationGroup.description, operationGroup.externalDocs, operationObject));
722 if(typeof this.apis[tag].help !== 'function')
723 this.apis[tag].help = this.help.bind(operationGroup);
724 // bind to the apis object
725 this.apis[tag][operationId] = operationObject.execute.bind(operationObject);
726 this.apis[tag][operationId].help = operationObject.help.bind(operationObject);
727 this.apis[tag][operationId].asCurl = operationObject.asCurl.bind(operationObject);
728 operationGroup[operationId] = operationObject.execute.bind(operationObject);
729 operationGroup[operationId].help = operationObject.help.bind(operationObject);
730 operationGroup[operationId].asCurl = operationObject.asCurl.bind(operationObject);
732 operationGroup.apis.push(operationObject);
733 operationGroup.operations[operationId] = operationObject;
738 for(j = 0; j < this.apisArray.length; j++) {
739 if(this.apisArray[j].tag === tag) {
740 api = this.apisArray[j];
744 api.operationsArray.push(operationObject);
749 log('no group to bind to');
763 SwaggerClient.prototype.parseUri = function(uri) {
764 var urlParseRE = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/;
765 var parts = urlParseRE.exec(uri);
767 scheme: parts[4].replace(':',''),
774 SwaggerClient.prototype.help = function(dontPrint) {
776 var output = 'operations for the "' + this.label + '" tag';
777 for(i = 0; i < this.apis.length; i++) {
778 var api = this.apis[i];
779 output += '\n * ' + api.nickname + ': ' + api.operation.summary;
789 SwaggerClient.prototype.tagFromLabel = function(label) {
793 SwaggerClient.prototype.idFromOp = function(path, httpMethod, op) {
794 var opId = op.operationId || (path.substring(1) + '_' + httpMethod);
795 return opId.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()\+\s]/g,'_');
798 SwaggerClient.prototype.fail = function(message) {
799 this.failure(message);
803 var OperationGroup = function(tag, description, externalDocs, operation) {
806 this.description = description;
807 this.externalDocs = externalDocs;
809 this.operation = operation;
810 this.operationsArray = [];
813 var Operation = function(parent, scheme, operationId, httpMethod, path, args, definitions) {
818 this.operations = {};
819 this.operation = args;
820 this.deprecated = args.deprecated;
821 this.consumes = args.consumes;
822 this.produces = args.produces;
823 this.parent = parent;
824 this.host = parent.host || 'localhost';
825 this.schemes = parent.schemes;
826 this.scheme = scheme || parent.scheme || 'http';
827 // this.basePath = window.location.pathname.split("/api-doc")[0]+parent.basePath || '/';
828 // var url = window.location.search.match(/\?url=(.*)\/.*.json.*$/);
830 if (window.location.search && window.location.search.length > 1) {
831 url = window.location.search.split("&api=")[1];
835 // if(url.lastIndexOf("runtime")>0){
836 // var realUrl = window.location.search.match(/\&api=(.*)$/);
842 url = "/api/microservices/v1";
849 this.nickname = (operationId||errors.push('Operations must have a nickname.'));
850 this.method = (httpMethod||errors.push('Operation ' + operationId + ' is missing method.'));
851 this.path = (path||errors.push('Operation ' + this.nickname + ' is missing path.'));
852 this.parameters = args !== null ? (args.parameters||[]) : {};
853 this.summary = args.summary || '';
854 this.responses = (args.responses||{});
856 this.security = args.security;
857 this.authorizations = args.security;
858 this.description = args.description;
859 this.useJQuery = parent.useJQuery;
861 if(typeof this.deprecated === 'string') {
862 switch(this.deprecated.toLowerCase()) {
863 case 'true': case 'yes': case '1': {
864 this.deprecated = true;
867 case 'false': case 'no': case '0': case null: {
868 this.deprecated = false;
871 default: this.deprecated = Boolean(this.deprecated);
878 // add to global models
880 for(key in this.definitions) {
881 model = new Model(key, definitions[key]);
887 for(i = 0; i < this.parameters.length; i++) {
888 var param = this.parameters[i];
889 if(param.type === 'array') {
891 param.allowMultiple = true;
893 var innerType = this.getType(param);
894 if(innerType && innerType.toString().toLowerCase() === 'boolean') {
895 param.allowableValues = {};
897 param['enum'] = ["true", "false"];
899 if(typeof param['enum'] !== 'undefined') {
901 param.allowableValues = {};
902 param.allowableValues.values = [];
903 param.allowableValues.descriptiveValues = [];
904 for(id = 0; id < param['enum'].length; id++) {
905 var value = param['enum'][id];
906 var isDefault = (value === param.default) ? true : false;
907 param.allowableValues.values.push(value);
908 param.allowableValues.descriptiveValues.push({value : value, isDefault: isDefault});
911 if(param.type === 'array') {
912 innerType = [innerType];
913 if(typeof param.allowableValues === 'undefined') {
914 // can't show as a list if no values to select from
916 delete param.allowMultiple;
919 param.signature = this.getModelSignature(innerType, models).toString();
920 param.sampleJSON = this.getModelSampleJSON(innerType, models);
921 param.responseClassSignature = param.signature;
924 var defaultResponseCode, response, responses = this.responses;
926 if(responses['200']) {
927 response = responses['200'];
928 defaultResponseCode = '200';
930 else if(responses['201']) {
931 response = responses['201'];
932 defaultResponseCode = '201';
934 else if(responses['202']) {
935 response = responses['202'];
936 defaultResponseCode = '202';
938 else if(responses['203']) {
939 response = responses['203'];
940 defaultResponseCode = '203';
942 else if(responses['204']) {
943 response = responses['204'];
944 defaultResponseCode = '204';
946 else if(responses['205']) {
947 response = responses['205'];
948 defaultResponseCode = '205';
950 else if(responses['206']) {
951 response = responses['206'];
952 defaultResponseCode = '206';
954 else if(responses['default']) {
955 response = responses['default'];
956 defaultResponseCode = 'default';
959 if(response && response.schema) {
960 var resolvedModel = this.resolveModel(response.schema, definitions);
961 delete responses[defaultResponseCode];
963 this.successResponse = {};
964 this.successResponse[defaultResponseCode] = resolvedModel;
967 this.successResponse = {};
968 this.successResponse[defaultResponseCode] = response.schema.type;
970 this.type = response;
973 if (errors.length > 0) {
974 if(this.resource && this.resource.api && this.resource.api.fail)
975 this.resource.api.fail(errors);
981 OperationGroup.prototype.sort = function(sorter) {
985 Operation.prototype.getType = function (param) {
986 var type = param.type;
987 var format = param.format;
990 if(type === 'integer' && format === 'int32')
992 else if(type === 'integer' && format === 'int64')
994 else if(type === 'integer')
996 else if(type === 'string') {
997 if(format === 'date-time')
999 else if(format === 'date')
1004 else if(type === 'number' && format === 'float')
1006 else if(type === 'number' && format === 'double')
1008 else if(type === 'number')
1010 else if(type === 'boolean')
1012 else if(type === 'array') {
1015 str = this.getType(param.items);
1020 var schema = param.schema;
1022 var ref = schema.$ref;
1024 ref = simpleRef(ref);
1031 return this.getType(schema);
1039 Operation.prototype.resolveModel = function (schema, definitions) {
1040 if(typeof schema.$ref !== 'undefined') {
1041 var ref = schema.$ref;
1042 if(ref.indexOf('#/definitions/') === 0)
1043 ref = ref.substring('#/definitions/'.length);
1044 if(definitions[ref]) {
1045 return new Model(ref, definitions[ref]);
1048 if(schema.type === 'array')
1049 return new ArrayModel(schema);
1054 Operation.prototype.help = function(dontPrint) {
1055 var out = this.nickname + ': ' + this.summary + '\n';
1056 for(var i = 0; i < this.parameters.length; i++) {
1057 var param = this.parameters[i];
1058 var typeInfo = param.signature;
1059 out += '\n * ' + param.name + ' (' + typeInfo + '): ' + param.description;
1061 if(typeof dontPrint === 'undefined')
1066 Operation.prototype.getModelSignature = function(type, definitions) {
1067 var isPrimitive, listType;
1069 if(type instanceof Array) {
1073 else if(typeof type === 'undefined')
1076 if(type === 'string')
1079 isPrimitive = (listType && definitions[listType]) || (definitions[type]) ? false : true;
1082 return 'Array[' + type + ']';
1084 return type.toString();
1087 return 'Array[' + definitions[type].getMockSignature() + ']';
1089 return definitions[type].getMockSignature();
1093 Operation.prototype.supportHeaderParams = function () {
1097 Operation.prototype.supportedSubmitMethods = function () {
1098 return this.parent.supportedSubmitMethods;
1101 Operation.prototype.getHeaderParams = function (args) {
1102 var headers = this.setContentTypes(args, {});
1103 for(var i = 0; i < this.parameters.length; i++) {
1104 var param = this.parameters[i];
1105 if(typeof args[param.name] !== 'undefined') {
1106 if (param.in === 'header') {
1107 var value = args[param.name];
1108 if(Array.isArray(value))
1109 value = value.toString();
1110 headers[param.name] = value;
1117 Operation.prototype.urlify = function (args) {
1118 var formParams = {};
1119 var requestUrl = this.path;
1121 // grab params from the args, build the querystring along the way
1122 var querystring = '';
1123 for(var i = 0; i < this.parameters.length; i++) {
1124 var param = this.parameters[i];
1125 if(typeof args[param.name] !== 'undefined') {
1126 if(param.in === 'path') {
1127 var reg = new RegExp('\{' + param.name + '\}', 'gi');
1128 var value = args[param.name];
1129 if(Array.isArray(value))
1130 value = this.encodePathCollection(param.collectionFormat, param.name, value);
1132 value = this.encodePathParam(value);
1133 requestUrl = requestUrl.replace(reg, value);
1135 else if (param.in === 'query' && typeof args[param.name] !== 'undefined') {
1136 if(querystring === '')
1140 if(typeof param.collectionFormat !== 'undefined') {
1141 var qp = args[param.name];
1142 if(Array.isArray(qp))
1143 querystring += this.encodeQueryCollection(param.collectionFormat, param.name, qp);
1145 querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
1148 querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
1150 else if (param.in === 'formData')
1151 formParams[param.name] = args[param.name];
1154 var url = this.scheme + '://' + this.host;
1156 if(this.basePath !== '/')
1157 url += this.basePath;
1159 return url + requestUrl + querystring;
1162 Operation.prototype.getMissingParams = function(args) {
1163 var missingParams = [];
1164 // check required params, track the ones that are missing
1166 for(i = 0; i < this.parameters.length; i++) {
1167 var param = this.parameters[i];
1168 if(param.required === true) {
1169 if(typeof args[param.name] === 'undefined')
1170 missingParams = param.name;
1173 return missingParams;
1176 Operation.prototype.getBody = function(headers, args, opts) {
1177 var formParams = {}, body, key;
1179 for(var i = 0; i < this.parameters.length; i++) {
1180 var param = this.parameters[i];
1181 if(typeof args[param.name] !== 'undefined') {
1182 if (param.in === 'body') {
1183 body = args[param.name];
1184 } else if(param.in === 'formData') {
1185 formParams[param.name] = args[param.name];
1190 // handle form params
1191 if(headers['Content-Type'] === 'application/x-www-form-urlencoded') {
1193 for(key in formParams) {
1194 value = formParams[key];
1195 if(typeof value !== 'undefined'){
1198 encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
1203 else if (headers['Content-Type'] && headers['Content-Type'].indexOf('multipart/form-data') >= 0) {
1204 if(opts.useJQuery) {
1205 var bodyParam = new FormData();
1206 bodyParam.type = 'formData';
1207 for (key in formParams) {
1209 if (typeof value !== 'undefined') {
1210 // required for jquery file upload
1211 if(value.type === 'file' && value.value) {
1212 delete headers['Content-Type'];
1213 bodyParam.append(key, value.value);
1216 bodyParam.append(key, value);
1227 * gets sample response for a single operation
1229 Operation.prototype.getModelSampleJSON = function(type, models) {
1230 var isPrimitive, listType, sampleJson;
1232 listType = (type instanceof Array);
1233 isPrimitive = models[type] ? false : true;
1234 sampleJson = isPrimitive ? void 0 : models[type].createJSONSample();
1236 sampleJson = listType ? [sampleJson] : sampleJson;
1237 if(typeof sampleJson == 'string')
1239 else if(typeof sampleJson === 'object') {
1241 if(sampleJson instanceof Array && sampleJson.length > 0) {
1245 var xmlString = new XMLSerializer().serializeToString(t);
1246 return this.formatXml(xmlString);
1249 return JSON.stringify(sampleJson, null, 2);
1259 Operation.prototype["do"] = function(args, opts, callback, error, parent) {
1260 return this.execute(args, opts, callback, error, parent);
1265 * executes an operation
1267 Operation.prototype.execute = function(arg1, arg2, arg3, arg4, parent) {
1268 var args = arg1 || {};
1269 var opts = {}, success, error;
1270 if(typeof arg2 === 'object') {
1276 if(typeof arg2 === 'function') {
1281 success = (success||log);
1282 error = (error||log);
1285 this.useJQuery = opts.useJQuery;
1287 var missingParams = this.getMissingParams(args);
1288 if(missingParams.length > 0) {
1289 var message = 'missing required params: ' + missingParams;
1293 var allHeaders = this.getHeaderParams(args);
1294 var contentTypeHeaders = this.setContentTypes(args, opts);
1296 var headers = {}, attrname;
1297 for (attrname in allHeaders) { headers[attrname] = allHeaders[attrname]; }
1298 for (attrname in contentTypeHeaders) { headers[attrname] = contentTypeHeaders[attrname]; }
1300 var body = this.getBody(headers, args, opts);
1301 var url = this.urlify(args);
1305 method: this.method.toUpperCase(),
1307 useJQuery: this.useJQuery,
1310 response: function(response) {
1311 return success(response, parent);
1313 error: function(response) {
1314 return error(response, parent);
1318 var status = authorizations.apply(obj, this.operation.security);
1319 if(opts.mock === true)
1322 new SwaggerHttp().execute(obj, opts);
1325 Operation.prototype.setContentTypes = function(args, opts) {
1327 var accepts = 'application/json';
1328 var consumes = args.parameterContentType || 'application/json';
1329 var allDefinedParams = this.parameters;
1330 var definedFormParams = [];
1331 var definedFileParams = [];
1335 // get params from the operation and set them in definedFileParams, definedFormParams, headers
1337 for(i = 0; i < allDefinedParams.length; i++) {
1338 var param = allDefinedParams[i];
1339 if(param.in === 'formData') {
1340 if(param.type === 'file')
1341 definedFileParams.push(param);
1343 definedFormParams.push(param);
1345 else if(param.in === 'header' && opts) {
1346 var key = param.name;
1347 var headerValue = opts[param.name];
1348 if(typeof opts[param.name] !== 'undefined')
1349 headers[key] = headerValue;
1351 else if(param.in === 'body' && typeof args[param.name] !== 'undefined') {
1352 body = args[param.name];
1356 // if there's a body, need to set the consumes header via requestContentType
1357 if (body && (this.method === 'post' || this.method === 'put' || this.method === 'patch' || this.method === 'delete')) {
1358 if (opts.requestContentType)
1359 consumes = opts.requestContentType;
1361 // if any form params, content type must be set
1362 if(definedFormParams.length > 0) {
1363 if(opts.requestContentType) // override if set
1364 consumes = opts.requestContentType;
1365 else if(definedFileParams.length > 0) // if a file, must be multipart/form-data
1366 consumes = 'multipart/form-data';
1367 else // default to x-www-from-urlencoded
1368 consumes = 'application/x-www-form-urlencoded';
1370 else if (this.type == 'DELETE')
1372 else if (this.type != 'DELETE')
1376 if (consumes && this.consumes) {
1377 if (this.consumes.indexOf(consumes) === -1) {
1378 log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.consumes));
1382 if (opts.responseContentType) {
1383 accepts = opts.responseContentType;
1385 accepts = 'application/json';
1387 if (accepts && this.produces) {
1388 if (this.produces.indexOf(accepts) === -1) {
1389 log('server can\'t produce ' + accepts);
1393 if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded'))
1394 headers['Content-Type'] = consumes;
1396 headers.Accept = accepts;
1400 Operation.prototype.asCurl = function (args) {
1401 var obj = this.execute(args, {mock: true});
1402 authorizations.apply(obj);
1404 results.push('-X ' + this.method.toUpperCase());
1407 for (key in obj.headers)
1408 results.push('--header "' + key + ': ' + obj.headers[key] + '"');
1412 if(typeof obj.body === 'object')
1413 body = JSON.stringify(obj.body);
1416 results.push('-d "' + body.replace(/"/g, '\\"') + '"');
1418 return 'curl ' + (results.join(' ')) + ' "' + obj.url + '"';
1421 Operation.prototype.encodePathCollection = function(type, name, value) {
1427 else if(type === 'tsv')
1429 else if(type === 'pipes')
1434 for(i = 0; i < value.length; i++) {
1436 encoded = this.encodeQueryParam(value[i]);
1438 encoded += separator + this.encodeQueryParam(value[i]);
1443 Operation.prototype.encodeQueryCollection = function(type, name, value) {
1446 if(type === 'default' || type === 'multi') {
1447 for(i = 0; i < value.length; i++) {
1448 if(i > 0) encoded += '&';
1449 encoded += this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
1456 else if(type === 'ssv')
1458 else if(type === 'tsv')
1460 else if(type === 'pipes')
1462 else if(type === 'brackets') {
1463 for(i = 0; i < value.length; i++) {
1466 encoded += this.encodeQueryParam(name) + '[]=' + this.encodeQueryParam(value[i]);
1469 if(separator !== '') {
1470 for(i = 0; i < value.length; i++) {
1472 encoded = this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
1474 encoded += separator + this.encodeQueryParam(value[i]);
1481 Operation.prototype.encodeQueryParam = function(arg) {
1482 return encodeURIComponent(arg);
1486 * TODO revisit, might not want to leave '/'
1488 Operation.prototype.encodePathParam = function(pathParam) {
1489 var encParts, part, parts, i, len;
1490 pathParam = pathParam.toString();
1491 if (pathParam.indexOf('/') === -1) {
1492 return encodeURIComponent(pathParam);
1494 parts = pathParam.split('/');
1496 for (i = 0, len = parts.length; i < len; i++) {
1497 encParts.push(encodeURIComponent(parts[i]));
1499 return encParts.join('/');
1503 var Model = function(name, definition) {
1505 this.definition = definition || {};
1506 this.properties = [];
1507 var requiredFields = definition.required || [];
1508 if(definition.type === 'array') {
1509 var out = new ArrayModel(definition);
1513 var props = definition.properties;
1516 var required = false;
1517 var property = props[key];
1518 if(requiredFields.indexOf(key) >= 0)
1520 this.properties.push(new Property(key, property, required));
1525 Model.prototype.createJSONSample = function(modelsToIgnore) {
1526 var i, result = {}, representations = {};
1527 modelsToIgnore = (modelsToIgnore||{});
1528 modelsToIgnore[this.name] = this;
1529 for (i = 0; i < this.properties.length; i++) {
1530 prop = this.properties[i];
1531 var sample = prop.getSampleValue(modelsToIgnore, representations);
1532 result[prop.name] = sample;
1534 delete modelsToIgnore[this.name];
1538 Model.prototype.getSampleValue = function(modelsToIgnore) {
1539 var i, obj = {}, representations = {};
1540 for(i = 0; i < this.properties.length; i++ ) {
1541 var property = this.properties[i];
1542 obj[property.name] = property.sampleValue(false, modelsToIgnore, representations);
1547 Model.prototype.getMockSignature = function(modelsToIgnore) {
1548 var i, prop, propertiesStr = [];
1549 for (i = 0; i < this.properties.length; i++) {
1550 prop = this.properties[i];
1551 propertiesStr.push(prop.toString());
1553 var strong = '<span class="strong">';
1554 var stronger = '<span class="stronger">';
1555 var strongClose = '</span>';
1556 var classOpen = strong + this.name + ' {' + strongClose;
1557 var classClose = strong + '}' + strongClose;
1558 var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
1559 if (!modelsToIgnore)
1560 modelsToIgnore = {};
1562 modelsToIgnore[this.name] = this;
1563 for (i = 0; i < this.properties.length; i++) {
1564 prop = this.properties[i];
1565 var ref = prop.$ref;
1566 var model = models[ref];
1567 if (model && typeof modelsToIgnore[model.name] === 'undefined') {
1568 returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
1574 var Property = function(name, obj, required) {
1576 this.required = required;
1578 this.$ref = simpleRef(obj.$ref);
1579 else if (obj.type === 'array' && obj.items) {
1581 this.$ref = simpleRef(obj.items.$ref);
1586 this.description = obj.description;
1588 this.optional = true;
1589 this.optional = !required;
1590 this.default = obj.default || null;
1591 this.example = obj.example !== undefined ? obj.example : null;
1592 this.collectionFormat = obj.collectionFormat || null;
1593 this.maximum = obj.maximum || null;
1594 this.exclusiveMaximum = obj.exclusiveMaximum || null;
1595 this.minimum = obj.minimum || null;
1596 this.exclusiveMinimum = obj.exclusiveMinimum || null;
1597 this.maxLength = obj.maxLength || null;
1598 this.minLength = obj.minLength || null;
1599 this.pattern = obj.pattern || null;
1600 this.maxItems = obj.maxItems || null;
1601 this.minItems = obj.minItems || null;
1602 this.uniqueItems = obj.uniqueItems || null;
1603 this['enum'] = obj['enum'] || null;
1604 this.multipleOf = obj.multipleOf || null;
1607 Property.prototype.getSampleValue = function (modelsToIgnore, representations) {
1608 return this.sampleValue(false, modelsToIgnore, representations);
1611 Property.prototype.isArray = function () {
1612 var schema = this.schema;
1613 if(schema.type === 'array')
1619 Property.prototype.sampleValue = function(isArray, ignoredModels, representations) {
1620 isArray = (isArray || this.isArray());
1621 ignoredModels = (ignoredModels || {});
1622 // representations = (representations || {});
1624 var type = getStringSignature(this.obj, true);
1628 var refModelName = simpleRef(this.$ref);
1629 var refModel = models[refModelName];
1630 if(typeof representations[type] !== 'undefined') {
1631 return representations[type];
1635 if(refModel && typeof ignoredModels[type] === 'undefined') {
1636 ignoredModels[type] = this;
1637 output = refModel.getSampleValue(ignoredModels, representations);
1638 representations[type] = output;
1641 output = (representations[type] || refModelName);
1644 else if(this.example)
1645 output = this.example;
1646 else if(this.default)
1647 output = this.default;
1648 else if(type === 'date-time')
1649 output = new Date().toISOString();
1650 else if(type === 'date')
1651 output = new Date().toISOString().split("T")[0];
1652 else if(type === 'string')
1654 else if(type === 'integer')
1656 else if(type === 'long')
1658 else if(type === 'float')
1660 else if(type === 'double')
1662 else if(type === 'boolean')
1666 ignoredModels[type] = output;
1673 getStringSignature = function(obj, baseComponent) {
1675 if(typeof obj.$ref !== 'undefined')
1676 str += simpleRef(obj.$ref);
1677 else if(typeof obj.type === 'undefined')
1679 else if(obj.type === 'array') {
1681 str += getStringSignature((obj.items || obj.$ref || {}));
1684 str += getStringSignature((obj.items || obj.$ref || {}));
1688 else if(obj.type === 'integer' && obj.format === 'int32')
1690 else if(obj.type === 'integer' && obj.format === 'int64')
1692 else if(obj.type === 'integer' && typeof obj.format === 'undefined')
1694 else if(obj.type === 'string' && obj.format === 'date-time')
1696 else if(obj.type === 'string' && obj.format === 'date')
1698 else if(obj.type === 'string' && typeof obj.format === 'undefined')
1700 else if(obj.type === 'number' && obj.format === 'float')
1702 else if(obj.type === 'number' && obj.format === 'double')
1704 else if(obj.type === 'number' && typeof obj.format === 'undefined')
1706 else if(obj.type === 'boolean')
1709 str += simpleRef(obj.$ref);
1715 simpleRef = function(name) {
1716 if(typeof name === 'undefined')
1718 if(name.indexOf("#/definitions/") === 0)
1719 return name.substring('#/definitions/'.length);
1724 Property.prototype.toString = function() {
1725 var str = getStringSignature(this.obj);
1727 str = '<span class="propName ' + this.required + '">' + this.name + '</span> (<span class="propType">' + str + '</span>';
1729 str += ', <span class="propOptKey">optional</span>';
1733 str = this.name + ' (' + JSON.stringify(this.obj) + ')';
1735 if(typeof this.description !== 'undefined')
1736 str += ': ' + this.description;
1739 str += ' = <span class="propVals">[\'' + this['enum'].join('\' or \'') + '\']</span>';
1742 str += ': <span class="propDesc">' + this.descr + '</span>';
1747 var isArray = this.schema.type === 'array';
1751 if(this.schema.items)
1752 type = this.schema.items.type;
1757 type = this.schema.type;
1761 options += optionHtml('Default', this.default);
1766 options += optionHtml('Min. Length', this.minLength);
1768 options += optionHtml('Max. Length', this.maxLength);
1770 options += optionHtml('Reg. Exp.', this.pattern);
1775 options += optionHtml('Min. Value', this.minimum);
1776 if (this.exclusiveMinimum)
1777 options += optionHtml('Exclusive Min.', "true");
1779 options += optionHtml('Max. Value', this.maximum);
1780 if (this.exclusiveMaximum)
1781 options += optionHtml('Exclusive Max.', "true");
1782 if (this.multipleOf)
1783 options += optionHtml('Multiple Of', this.multipleOf);
1789 options += optionHtml('Min. Items', this.minItems);
1791 options += optionHtml('Max. Items', this.maxItems);
1792 if (this.uniqueItems)
1793 options += optionHtml('Unique Items', "true");
1794 if (this.collectionFormat)
1795 options += optionHtml('Coll. Format', this.collectionFormat);
1801 if (type === 'number' || type === 'integer')
1802 enumString = this['enum'].join(', ');
1804 enumString = '"' + this['enum'].join('", "') + '"';
1807 options += optionHtml('Enum', enumString);
1810 if (options.length > 0)
1811 str = '<span class="propWrap">' + str + '<table class="optionsWrapper"><tr><th colspan="2">' + this.name + '</th></tr>' + options + '</table></span>';
1816 optionHtml = function(label, value) {
1817 return '<tr><td class="optionName">' + label + ':</td><td>' + value + '</td></tr>';
1820 typeFromJsonSchema = function(type, format) {
1822 if(type === 'integer' && format === 'int32')
1824 else if(type === 'integer' && format === 'int64')
1826 else if(type === 'integer' && typeof format === 'undefined')
1828 else if(type === 'string' && format === 'date-time')
1830 else if(type === 'string' && format === 'date')
1832 else if(type === 'number' && format === 'float')
1834 else if(type === 'number' && format === 'double')
1836 else if(type === 'number' && typeof format === 'undefined')
1838 else if(type === 'boolean')
1840 else if(type === 'string')
1846 var sampleModels = {};
1850 SwaggerClient.prototype.buildFrom1_2Spec = function (response) {
1851 if (response.apiVersion !== null) {
1852 this.apiVersion = response.apiVersion;
1855 this.apisArray = [];
1856 this.consumes = response.consumes;
1857 this.produces = response.produces;
1858 this.authSchemes = response.authorizations;
1859 this.info = this.convertInfo(response.info);
1861 var isApi = false, i, res;
1862 for (i = 0; i < response.apis.length; i++) {
1863 var api = response.apis[i];
1864 if (api.operations) {
1866 for (j = 0; j < api.operations.length; j++) {
1867 operation = api.operations[j];
1872 if (response.basePath)
1873 this.basePath = response.basePath;
1874 else if (this.url.indexOf('?') > 0)
1875 this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
1877 this.basePath = this.url;
1880 var newName = response.resourcePath.replace(/\//g, '');
1881 this.resourcePath = response.resourcePath;
1882 res = new SwaggerResource(response, this);
1883 this.apis[newName] = res;
1884 this.apisArray.push(res);
1888 this.expectedResourceCount = response.apis.length;
1889 for (k = 0; k < response.apis.length; k++) {
1890 var resource = response.apis[k];
1891 res = new SwaggerResource(resource, this);
1892 this.apis[res.name] = res;
1893 this.apisArray.push(res);
1896 this.isValid = true;
1900 SwaggerClient.prototype.finish = function() {
1901 if (typeof this.success === 'function') {
1902 this.isValid = true;
1904 this.isBuilt = true;
1910 SwaggerClient.prototype.buildFrom1_1Spec = function (response) {
1911 log('This API is using a deprecated version of Swagger! Please see http://github.com/wordnik/swagger-core/wiki for more info');
1912 if (response.apiVersion !== null)
1913 this.apiVersion = response.apiVersion;
1915 this.apisArray = [];
1916 this.produces = response.produces;
1917 this.info = this.convertInfo(response.info);
1918 var isApi = false, res;
1919 for (var i = 0; i < response.apis.length; i++) {
1920 var api = response.apis[i];
1921 if (api.operations) {
1922 for (var j = 0; j < api.operations.length; j++) {
1923 operation = api.operations[j];
1928 if (response.basePath) {
1929 this.basePath = response.basePath;
1930 } else if (this.url.indexOf('?') > 0) {
1931 this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
1933 this.basePath = this.url;
1936 var newName = response.resourcePath.replace(/\//g, '');
1937 this.resourcePath = response.resourcePath;
1938 res = new SwaggerResource(response, this);
1939 this.apis[newName] = res;
1940 this.apisArray.push(res);
1943 this.expectedResourceCount = response.apis.length;
1944 for (k = 0; k < response.apis.length; k++) {
1945 resource = response.apis[k];
1946 res = new SwaggerResource(resource, this);
1947 this.apis[res.name] = res;
1948 this.apisArray.push(res);
1951 this.isValid = true;
1955 SwaggerClient.prototype.convertInfo = function (resp) {
1956 if(typeof resp == 'object') {
1959 info.title = resp.title;
1960 info.description = resp.description;
1961 info.termsOfService = resp.termsOfServiceUrl;
1963 info.contact.name = resp.contact;
1965 info.license.name = resp.license;
1966 info.license.url = resp.licenseUrl;
1972 SwaggerClient.prototype.selfReflect = function () {
1973 var resource, tag, ref;
1974 if (this.apis === null) {
1980 if (api.ready === null) {
1984 this[tag].help = __bind(api.help, api);
1986 this.setConsolidatedModels();
1990 SwaggerClient.prototype.setConsolidatedModels = function () {
1991 var model, modelName, resource, resource_name, i, apis, models, results;
1994 for (resource_name in apis) {
1995 resource = apis[resource_name];
1996 for (modelName in resource.models) {
1997 if (typeof this.models[modelName] === 'undefined') {
1998 this.models[modelName] = resource.models[modelName];
1999 this.modelsArray.push(resource.models[modelName]);
2003 models = this.modelsArray;
2005 for (i = 0; i < models.length; i++) {
2007 results.push(model.setReferencedModels(this.models));
2012 var SwaggerResource = function (resourceObj, api) {
2015 this.swaggerRequstHeaders = api.swaggerRequstHeaders;
2016 this.path = (typeof this.api.resourcePath === 'string') ? this.api.resourcePath : resourceObj.path;
2017 this.description = resourceObj.description;
2018 this.authorizations = (resourceObj.authorizations || {});
2020 var parts = this.path.split('/');
2021 this.name = parts[parts.length - 1].replace('.{format}', '');
2022 this.basePath = this.api.basePath;
2023 this.operations = {};
2024 this.operationsArray = [];
2025 this.modelsArray = [];
2026 this.models = api.models || {};
2027 this.rawModels = {};
2028 this.useJQuery = (typeof api.useJQuery !== 'undefined') ? api.useJQuery : null;
2030 if ((resourceObj.apis) && this.api.resourcePath) {
2031 this.addApiDeclaration(resourceObj);
2033 if (typeof this.path === 'undefined') {
2034 this.api.fail('SwaggerResources must have a path.');
2036 if (this.path.substring(0, 4) === 'http') {
2037 this.url = this.path.replace('{format}', 'json');
2039 this.url = this.api.basePath + this.path.replace('{format}', 'json');
2041 this.api.progress('fetching resource ' + this.name + ': ' + this.url);
2045 useJQuery: this.useJQuery,
2047 accept: this.swaggerRequstHeaders
2050 response: function (resp) {
2051 var responseObj = resp.obj || JSON.parse(resp.data);
2052 _this.api.resourceCount += 1;
2053 return _this.addApiDeclaration(responseObj);
2055 error: function (response) {
2056 _this.api.resourceCount += 1;
2057 return _this.api.fail('Unable to read api \'' +
2058 _this.name + '\' from path ' + _this.url + ' (server returned ' + response.statusText + ')');
2062 var e = typeof window !== 'undefined' ? window : exports;
2063 e.authorizations.apply(obj);
2064 new SwaggerHttp().execute(obj);
2068 SwaggerResource.prototype.help = function (dontPrint) {
2070 var output = 'operations for the "' + this.name + '" tag';
2071 for(i = 0; i < this.operationsArray.length; i++) {
2072 var api = this.operationsArray[i];
2073 output += '\n * ' + api.nickname + ': ' + api.description;
2083 SwaggerResource.prototype.getAbsoluteBasePath = function (relativeBasePath) {
2085 url = this.api.basePath;
2086 pos = url.lastIndexOf(relativeBasePath);
2087 var parts = url.split('/');
2088 var rootUrl = parts[0] + '//' + parts[2];
2090 if (relativeBasePath.indexOf('http') === 0)
2091 return relativeBasePath;
2092 if (relativeBasePath === '/')
2094 if (relativeBasePath.substring(0, 1) == '/') {
2095 // use root + relative
2096 return rootUrl + relativeBasePath;
2099 pos = this.basePath.lastIndexOf('/');
2100 var base = this.basePath.substring(0, pos);
2101 if (base.substring(base.length - 1) == '/')
2102 return base + relativeBasePath;
2104 return base + '/' + relativeBasePath;
2108 SwaggerResource.prototype.addApiDeclaration = function (response) {
2109 if (typeof response.produces === 'string')
2110 this.produces = response.produces;
2111 if (typeof response.consumes === 'string')
2112 this.consumes = response.consumes;
2113 if ((typeof response.basePath === 'string') && response.basePath.replace(/\s/g, '').length > 0)
2114 this.basePath = response.basePath.indexOf('http') === -1 ? this.getAbsoluteBasePath(response.basePath) : response.basePath;
2115 this.resourcePath = response.resourcePath;
2116 this.addModels(response.models);
2117 if (response.apis) {
2118 for (var i = 0 ; i < response.apis.length; i++) {
2119 var endpoint = response.apis[i];
2120 this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces);
2123 this.api[this.name] = this;
2125 if(this.api.resourceCount === this.api.expectedResourceCount)
2130 SwaggerResource.prototype.addModels = function (models) {
2131 if (typeof models === 'object') {
2133 for (modelName in models) {
2134 if (typeof this.models[modelName] === 'undefined') {
2135 var swaggerModel = new SwaggerModel(modelName, models[modelName]);
2136 this.modelsArray.push(swaggerModel);
2137 this.models[modelName] = swaggerModel;
2138 this.rawModels[modelName] = models[modelName];
2142 for (var i = 0; i < this.modelsArray.length; i++) {
2143 var model = this.modelsArray[i];
2144 output.push(model.setReferencedModels(this.models));
2150 SwaggerResource.prototype.addOperations = function (resource_path, ops, consumes, produces) {
2153 for (var i = 0; i < ops.length; i++) {
2155 consumes = this.consumes;
2156 produces = this.produces;
2157 if (typeof o.consumes !== 'undefined')
2158 consumes = o.consumes;
2160 consumes = this.consumes;
2162 if (typeof o.produces !== 'undefined')
2163 produces = o.produces;
2165 produces = this.produces;
2166 var type = (o.type || o.responseClass);
2168 if (type === 'array') {
2171 ref = o.items.type || o.items.$ref;
2172 type = 'array[' + ref + ']';
2174 var responseMessages = o.responseMessages;
2175 var method = o.method;
2177 method = o.httpMethod;
2179 if (o.supportedContentTypes) {
2180 consumes = o.supportedContentTypes;
2182 if (o.errorResponses) {
2183 responseMessages = o.errorResponses;
2184 for (var j = 0; j < responseMessages.length; j++) {
2185 r = responseMessages[j];
2186 r.message = r.reason;
2190 o.nickname = this.sanitize(o.nickname);
2191 var op = new SwaggerOperation(o.nickname,
2205 this.operations[op.nickname] = op;
2206 output.push(this.operationsArray.push(op));
2212 SwaggerResource.prototype.sanitize = function (nickname) {
2214 op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|.\/?,\\'""-]/g, '_');
2215 op = op.replace(/((_){2,})/g, '_');
2216 op = op.replace(/^(_)*/g, '');
2217 op = op.replace(/([_])*$/g, '');
2221 var SwaggerModel = function (modelName, obj) {
2222 this.name = typeof obj.id !== 'undefined' ? obj.id : modelName;
2223 this.properties = [];
2225 for (propertyName in obj.properties) {
2228 for (value in obj.required) {
2229 if (propertyName === obj.required[value]) {
2230 obj.properties[propertyName].required = true;
2234 var prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName], this);
2235 this.properties.push(prop);
2239 SwaggerModel.prototype.setReferencedModels = function (allModels) {
2241 for (var i = 0; i < this.properties.length; i++) {
2242 var property = this.properties[i];
2243 var type = property.type || property.dataType;
2244 if (allModels[type])
2245 results.push(property.refModel = allModels[type]);
2246 else if ((property.refDataType) && (allModels[property.refDataType]))
2247 results.push(property.refModel = allModels[property.refDataType]);
2249 results.push(void 0);
2254 SwaggerModel.prototype.getMockSignature = function (modelsToIgnore) {
2255 var i, prop, propertiesStr = [];
2256 for (i = 0; i < this.properties.length; i++) {
2257 prop = this.properties[i];
2258 propertiesStr.push(prop.toString());
2261 var strong = '<span class="strong">';
2262 var strongClose = '</span>';
2263 var classOpen = strong + this.name + ' {' + strongClose;
2264 var classClose = strong + '}' + strongClose;
2265 var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
2266 if (!modelsToIgnore)
2267 modelsToIgnore = [];
2268 modelsToIgnore.push(this.name);
2270 for (i = 0; i < this.properties.length; i++) {
2271 prop = this.properties[i];
2272 if ((prop.refModel) && modelsToIgnore.indexOf(prop.refModel.name) === -1) {
2273 returnVal = returnVal + ('<br>' + prop.refModel.getMockSignature(modelsToIgnore));
2279 SwaggerModel.prototype.createJSONSample = function (modelsToIgnore) {
2280 if (sampleModels[this.name]) {
2281 return sampleModels[this.name];
2285 modelsToIgnore = (modelsToIgnore || []);
2286 modelsToIgnore.push(this.name);
2287 for (var i = 0; i < this.properties.length; i++) {
2288 var prop = this.properties[i];
2289 result[prop.name] = prop.getSampleValue(modelsToIgnore);
2291 modelsToIgnore.pop(this.name);
2296 var SwaggerModelProperty = function (name, obj, model) {
2298 this.dataType = obj.type || obj.dataType || obj.$ref;
2299 this.isCollection = this.dataType && (this.dataType.toLowerCase() === 'array' || this.dataType.toLowerCase() === 'list' || this.dataType.toLowerCase() === 'set');
2300 this.descr = obj.description;
2301 this.required = obj.required;
2302 this.defaultValue = applyModelPropertyMacro(obj, model);
2304 if (obj.items.type) {
2305 this.refDataType = obj.items.type;
2307 if (obj.items.$ref) {
2308 this.refDataType = obj.items.$ref;
2311 this.dataTypeWithRef = this.refDataType ? (this.dataType + '[' + this.refDataType + ']') : this.dataType;
2312 if (obj.allowableValues) {
2313 this.valueType = obj.allowableValues.valueType;
2314 this.values = obj.allowableValues.values;
2316 this.valuesString = '\'' + this.values.join('\' or \'') + '\'';
2320 this.valueType = 'string';
2321 this.values = obj['enum'];
2323 this.valueString = '\'' + this.values.join('\' or \'') + '\'';
2328 SwaggerModelProperty.prototype.getSampleValue = function (modelsToIgnore) {
2330 if ((this.refModel) && (modelsToIgnore.indexOf(this.refModel.name) === -1)) {
2331 result = this.refModel.createJSONSample(modelsToIgnore);
2333 if (this.isCollection) {
2334 result = this.toSampleValue(this.refDataType);
2336 result = this.toSampleValue(this.dataType);
2339 if (this.isCollection) {
2346 SwaggerModelProperty.prototype.toSampleValue = function (value) {
2348 if ((typeof this.defaultValue !== 'undefined') && this.defaultValue) {
2349 result = this.defaultValue;
2350 } else if (value === 'integer') {
2352 } else if (value === 'boolean') {
2354 } else if (value === 'double' || value === 'number') {
2356 } else if (value === 'string') {
2364 SwaggerModelProperty.prototype.toString = function () {
2365 var req = this.required ? 'propReq' : 'propOpt';
2366 var str = '<span class="propName ' + req + '">' + this.name + '</span> (<span class="propType">' + this.dataTypeWithRef + '</span>';
2367 if (!this.required) {
2368 str += ', <span class="propOptKey">optional</span>';
2372 str += ' = <span class="propVals">[\'' + this.values.join('\' or \'') + '\']</span>';
2375 str += ': <span class="propDesc">' + this.descr + '</span>';
2380 var SwaggerOperation = function (nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations, deprecated) {
2384 this.nickname = (nickname || errors.push('SwaggerOperations must have a nickname.'));
2385 this.path = (path || errors.push('SwaggerOperation ' + nickname + ' is missing path.'));
2386 this.method = (method || errors.push('SwaggerOperation ' + nickname + ' is missing method.'));
2387 this.parameters = parameters ? parameters : [];
2388 this.summary = summary;
2391 this.responseMessages = (responseMessages || []);
2392 this.resource = (resource || errors.push('Resource is required'));
2393 this.consumes = consumes;
2394 this.produces = produces;
2395 this.authorizations = typeof authorizations !== 'undefined' ? authorizations : resource.authorizations;
2396 this.deprecated = deprecated;
2397 this['do'] = __bind(this['do'], this);
2400 if(typeof this.deprecated === 'string') {
2401 switch(this.deprecated.toLowerCase()) {
2402 case 'true': case 'yes': case '1': {
2403 this.deprecated = true;
2406 case 'false': case 'no': case '0': case null: {
2407 this.deprecated = false;
2410 default: this.deprecated = Boolean(this.deprecated);
2414 if (errors.length > 0) {
2415 console.error('SwaggerOperation errors', errors, arguments);
2416 this.resource.api.fail(errors);
2419 this.path = this.path.replace('{format}', 'json');
2420 this.method = this.method.toLowerCase();
2421 this.isGetMethod = this.method === 'get';
2424 this.resourceName = this.resource.name;
2425 if (typeof this.type !== 'undefined' && this.type === 'void')
2428 this.responseClassSignature = this.getSignature(this.type, this.resource.models);
2429 this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models);
2432 for (i = 0; i < this.parameters.length; i++) {
2433 var param = this.parameters[i];
2434 // might take this away
2435 param.name = param.name || param.type || param.dataType;
2436 // for 1.1 compatibility
2437 type = param.type || param.dataType;
2438 if (type === 'array') {
2439 type = 'array[' + (param.items.$ref ? param.items.$ref : param.items.type) + ']';
2443 if (type && type.toLowerCase() === 'boolean') {
2444 param.allowableValues = {};
2445 param.allowableValues.values = ['true', 'false'];
2447 param.signature = this.getSignature(type, this.resource.models);
2448 param.sampleJSON = this.getSampleJSON(type, this.resource.models);
2450 var enumValue = param['enum'];
2451 if (typeof enumValue !== 'undefined') {
2452 param.isList = true;
2453 param.allowableValues = {};
2454 param.allowableValues.descriptiveValues = [];
2456 for (j = 0; j < enumValue.length; j++) {
2458 if (param.defaultValue) {
2459 param.allowableValues.descriptiveValues.push({
2461 isDefault: (v === param.defaultValue)
2465 param.allowableValues.descriptiveValues.push({
2472 else if (param.allowableValues) {
2473 if (param.allowableValues.valueType === 'RANGE')
2474 param.isRange = true;
2476 param.isList = true;
2477 if (param.allowableValues) {
2478 param.allowableValues.descriptiveValues = [];
2479 if (param.allowableValues.values) {
2480 for (j = 0; j < param.allowableValues.values.length; j++) {
2481 v = param.allowableValues.values[j];
2482 if (param.defaultValue !== null) {
2483 param.allowableValues.descriptiveValues.push({
2485 isDefault: (v === param.defaultValue)
2489 param.allowableValues.descriptiveValues.push({
2498 param.defaultValue = applyParameterMacro(this, param);
2500 var defaultSuccessCallback = this.resource.api.defaultSuccessCallback || null;
2501 var defaultErrorCallback = this.resource.api.defaultErrorCallback || null;
2503 this.resource[this.nickname] = function (args, opts, callback, error) {
2504 var arg1, arg2, arg3, arg4;
2505 if(typeof args === 'function') { // right shift 3
2506 arg1 = {}; arg2 = {}; arg3 = args; arg4 = opts;
2508 else if(typeof args === 'object' && typeof opts === 'function') { // right shift 2
2509 arg1 = args; arg2 = {}; arg3 = opts; arg4 = callback;
2512 arg1 = args; arg2 = opts; arg3 = callback; arg4 = error;
2514 return _this['do'](arg1 || {}, arg2 || {}, arg3 || defaultSuccessCallback, arg4 || defaultErrorCallback);
2517 this.resource[this.nickname].help = function (dontPrint) {
2518 return _this.help(dontPrint);
2520 this.resource[this.nickname].asCurl = function (args) {
2521 return _this.asCurl(args);
2525 SwaggerOperation.prototype.isListType = function (type) {
2526 if (type && type.indexOf('[') >= 0) {
2527 return type.substring(type.indexOf('[') + 1, type.indexOf(']'));
2533 SwaggerOperation.prototype.getSignature = function (type, models) {
2534 var isPrimitive, listType;
2535 listType = this.isListType(type);
2536 isPrimitive = ((typeof listType !== 'undefined') && models[listType]) || (typeof models[type] !== 'undefined') ? false : true;
2540 if (typeof listType !== 'undefined') {
2541 return models[listType].getMockSignature();
2543 return models[type].getMockSignature();
2548 SwaggerOperation.prototype.getSampleJSON = function (type, models) {
2549 var isPrimitive, listType, val;
2550 listType = this.isListType(type);
2551 isPrimitive = ((typeof listType !== 'undefined') && models[listType]) || (typeof models[type] !== 'undefined') ? false : true;
2552 val = isPrimitive ? void 0 : (listType ? models[listType].createJSONSample() : models[type].createJSONSample());
2554 val = listType ? [val] : val;
2555 if (typeof val == 'string')
2557 else if (typeof val === 'object') {
2559 if (val instanceof Array && val.length > 0) {
2563 var xmlString = new XMLSerializer().serializeToString(t);
2564 return this.formatXml(xmlString);
2567 return JSON.stringify(val, null, 2);
2574 SwaggerOperation.prototype['do'] = function (args, opts, callback, error) {
2575 var key, param, params, possibleParams = [], req, value;
2577 if (typeof error !== 'function') {
2578 error = function (xhr, textStatus, error) {
2579 return log(xhr, textStatus, error);
2583 if (typeof callback !== 'function') {
2584 callback = function (response) {
2587 if (response !== null) {
2588 content = response.data;
2590 content = 'no data';
2592 return log('default callback: ' + content);
2597 params.headers = [];
2599 params.headers = args.headers;
2600 delete args.headers;
2602 // allow override from the opts
2603 if(opts && opts.responseContentType) {
2604 params.headers['Content-Type'] = opts.responseContentType;
2606 if(opts && opts.requestContentType) {
2607 params.headers.Accept = opts.requestContentType;
2610 for (var i = 0; i < this.parameters.length; i++) {
2611 param = this.parameters[i];
2612 if (param.paramType === 'header') {
2613 if (typeof args[param.name] !== 'undefined')
2614 params.headers[param.name] = args[param.name];
2616 else if (param.paramType === 'form' || param.paramType.toLowerCase() === 'file')
2617 possibleParams.push(param);
2618 else if (param.paramType === 'body' && param.name !== 'body' && typeof args[param.name] !== 'undefined') {
2620 throw new Error('Saw two body params in an API listing; expecting a max of one.');
2622 args.body = args[param.name];
2626 if (typeof args.body !== 'undefined') {
2627 params.body = args.body;
2631 if (possibleParams) {
2632 for (key in possibleParams) {
2633 value = possibleParams[key];
2634 if (args[value.name]) {
2635 params[value.name] = args[value.name];
2640 req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this);
2648 SwaggerOperation.prototype.pathJson = function () {
2649 return this.path.replace('{format}', 'json');
2652 SwaggerOperation.prototype.pathXml = function () {
2653 return this.path.replace('{format}', 'xml');
2656 SwaggerOperation.prototype.encodePathParam = function (pathParam) {
2657 var encParts, part, parts, _i, _len;
2658 pathParam = pathParam.toString();
2659 if (pathParam.indexOf('/') === -1) {
2660 return encodeURIComponent(pathParam);
2662 parts = pathParam.split('/');
2664 for (_i = 0, _len = parts.length; _i < _len; _i++) {
2666 encParts.push(encodeURIComponent(part));
2668 return encParts.join('/');
2672 SwaggerOperation.prototype.urlify = function (args) {
2673 var i, j, param, url;
2674 // ensure no double slashing...
2675 if(this.resource.basePath.length > 1 && this.resource.basePath.slice(-1) === '/' && this.pathJson().charAt(0) === '/')
2676 url = this.resource.basePath + this.pathJson().substring(1);
2678 url = this.resource.basePath + this.pathJson();
2679 var params = this.parameters;
2680 for (i = 0; i < params.length; i++) {
2682 if (param.paramType === 'path') {
2683 if (typeof args[param.name] !== 'undefined') {
2684 // apply path params and remove from args
2685 var reg = new RegExp('\\{\\s*?' + param.name + '[^\\{\\}\\/]*(?:\\{.*?\\}[^\\{\\}\\/]*)*\\}(?=(\\/?|$))', 'gi');
2686 url = url.replace(reg, this.encodePathParam(args[param.name]));
2687 delete args[param.name];
2690 throw '' + param.name + ' is a required path param.';
2694 var queryParams = '';
2695 for (i = 0; i < params.length; i++) {
2697 if(param.paramType === 'query') {
2698 if (queryParams !== '')
2700 if (Array.isArray(param)) {
2702 for(j = 0; j < param.length; j++) {
2705 output += encodeURIComponent(param[j]);
2707 queryParams += encodeURIComponent(param.name) + '=' + output;
2710 if (typeof args[param.name] !== 'undefined') {
2711 queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]);
2714 throw '' + param.name + ' is a required query param.';
2719 if ((queryParams) && queryParams.length > 0)
2720 url += '?' + queryParams;
2724 SwaggerOperation.prototype.supportHeaderParams = function () {
2725 return this.resource.api.supportHeaderParams;
2728 SwaggerOperation.prototype.supportedSubmitMethods = function () {
2729 return this.resource.api.supportedSubmitMethods;
2732 SwaggerOperation.prototype.getQueryParams = function (args) {
2733 return this.getMatchingParams(['query'], args);
2736 SwaggerOperation.prototype.getHeaderParams = function (args) {
2737 return this.getMatchingParams(['header'], args);
2740 SwaggerOperation.prototype.getMatchingParams = function (paramTypes, args) {
2741 var matchingParams = {};
2742 var params = this.parameters;
2743 for (var i = 0; i < params.length; i++) {
2745 if (args && args[param.name])
2746 matchingParams[param.name] = args[param.name];
2748 var headers = this.resource.api.headers;
2750 for (name in headers) {
2751 var value = headers[name];
2752 matchingParams[name] = value;
2754 return matchingParams;
2757 SwaggerOperation.prototype.help = function (dontPrint) {
2758 var msg = this.nickname + ': ' + this.summary;
2759 var params = this.parameters;
2760 for (var i = 0; i < params.length; i++) {
2761 var param = params[i];
2762 msg += '\n* ' + param.name + (param.required ? ' (required)' : '') + " - " + param.description;
2772 SwaggerOperation.prototype.asCurl = function (args) {
2776 var headers = SwaggerRequest.prototype.setHeaders(args, {}, this);
2777 for(i = 0; i < this.parameters.length; i++) {
2778 var param = this.parameters[i];
2779 if(param.paramType && param.paramType === 'header' && args[param.name]) {
2780 headers[param.name] = args[param.name];
2785 for (key in headers) {
2786 results.push('--header "' + key + ': ' + headers[key] + '"');
2788 return 'curl ' + (results.join(' ')) + ' ' + this.urlify(args);
2791 SwaggerOperation.prototype.formatXml = function (xml) {
2792 var contexp, formatted, indent, lastType, lines, ln, pad, reg, transitions, wsexp, _fn, _i, _len;
2793 reg = /(>)(<)(\/*)/g;
2794 wsexp = /[ ]*(.*)[ ]+\n/g;
2795 contexp = /(<.+>)(.+\n)/g;
2796 xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
2799 lines = xml.split('\n');
2803 'single->single': 0,
2804 'single->closing': -1,
2805 'single->opening': 0,
2807 'closing->single': 0,
2808 'closing->closing': -1,
2809 'closing->opening': 0,
2810 'closing->other': 0,
2811 'opening->single': 1,
2812 'opening->closing': 0,
2813 'opening->opening': 1,
2814 'opening->other': 1,
2816 'other->closing': -1,
2817 'other->opening': 0,
2820 _fn = function (ln) {
2821 var fromTo, j, key, padding, type, types, value;
2823 single: Boolean(ln.match(/<.+\/>/)),
2824 closing: Boolean(ln.match(/<\/.+>/)),
2825 opening: Boolean(ln.match(/<[^!?].*>/))
2827 type = ((function () {
2830 for (key in types) {
2838 type = type === void 0 ? 'other' : type;
2839 fromTo = lastType + '->' + type;
2842 indent += transitions[fromTo];
2843 padding = ((function () {
2844 var _j, _ref5, _results;
2846 for (j = _j = 0, _ref5 = indent; 0 <= _ref5 ? _j < _ref5 : _j > _ref5; j = 0 <= _ref5 ? ++_j : --_j) {
2851 if (fromTo === 'opening->closing') {
2852 formatted = formatted.substr(0, formatted.length - 1) + ln + '\n';
2854 formatted += padding + ln + '\n';
2857 for (_i = 0, _len = lines.length; _i < _len; _i++) {
2864 var SwaggerRequest = function (type, url, params, opts, successCallback, errorCallback, operation, execution) {
2868 this.useJQuery = (typeof operation.resource.useJQuery !== 'undefined' ? operation.resource.useJQuery : null);
2869 this.type = (type || errors.push('SwaggerRequest type is required (get/post/put/delete/patch/options).'));
2870 this.url = (url || errors.push('SwaggerRequest url is required.'));
2871 this.params = params;
2873 this.successCallback = (successCallback || errors.push('SwaggerRequest successCallback is required.'));
2874 this.errorCallback = (errorCallback || errors.push('SwaggerRequest error callback is required.'));
2875 this.operation = (operation || errors.push('SwaggerRequest operation is required.'));
2876 this.execution = execution;
2877 this.headers = (params.headers || {});
2879 if (errors.length > 0) {
2883 this.type = this.type.toUpperCase();
2885 // set request, response content type headers
2886 var headers = this.setHeaders(params, opts, this.operation);
2887 var body = params.body;
2889 // encode the body for form submits
2890 if (headers['Content-Type']) {
2891 var key, value, values = {}, i;
2892 var operationParams = this.operation.parameters;
2893 for (i = 0; i < operationParams.length; i++) {
2894 var param = operationParams[i];
2895 if (param.paramType === 'form')
2896 values[param.name] = param;
2899 if (headers['Content-Type'].indexOf('application/x-www-form-urlencoded') === 0) {
2901 for (key in values) {
2902 value = this.params[key];
2903 if (typeof value !== 'undefined') {
2906 encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
2911 else if (headers['Content-Type'].indexOf('multipart/form-data') === 0) {
2912 // encode the body for form submits
2914 var boundary = '----SwaggerFormBoundary' + Date.now();
2915 for (key in values) {
2916 value = this.params[key];
2917 if (typeof value !== 'undefined') {
2918 data += '--' + boundary + '\n';
2919 data += 'Content-Disposition: form-data; name="' + key + '"';
2921 data += value + '\n';
2924 data += '--' + boundary + '--\n';
2925 headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
2931 if (!((this.headers) && (this.headers.mock))) {
2937 useJQuery: this.useJQuery,
2939 error: function (response) {
2940 return _this.errorCallback(response, _this.opts.parent);
2942 redirect: function (response) {
2943 return _this.successCallback(response, _this.opts.parent);
2945 307: function (response) {
2946 return _this.successCallback(response, _this.opts.parent);
2948 response: function (response) {
2949 return _this.successCallback(response, _this.opts.parent);
2955 if (this.operation.resource && this.operation.resource.api && this.operation.resource.api.clientAuthorizations) {
2956 // Get the client authorizations from the resource declaration
2957 status = this.operation.resource.api.clientAuthorizations.apply(obj, this.operation.authorizations);
2959 // Get the client authorization from the default authorization declaration
2961 if (typeof window !== 'undefined') {
2966 status = e.authorizations.apply(obj, this.operation.authorizations);
2970 if (status !== false) {
2971 new SwaggerHttp().execute(obj);
2973 obj.canceled = true;
2982 SwaggerRequest.prototype.setHeaders = function (params, opts, operation) {
2984 var accepts = opts.responseContentType || 'application/json';
2985 var consumes = opts.requestContentType || 'application/json';
2987 var allDefinedParams = operation.parameters;
2988 var definedFormParams = [];
2989 var definedFileParams = [];
2990 var body = params.body;
2993 // get params from the operation and set them in definedFileParams, definedFormParams, headers
2995 for (i = 0; i < allDefinedParams.length; i++) {
2996 var param = allDefinedParams[i];
2997 if (param.paramType === 'form')
2998 definedFormParams.push(param);
2999 else if (param.paramType === 'file')
3000 definedFileParams.push(param);
3001 else if (param.paramType === 'header' && this.params.headers) {
3002 var key = param.name;
3003 var headerValue = this.params.headers[param.name];
3004 if (typeof this.params.headers[param.name] !== 'undefined')
3005 headers[key] = headerValue;
3009 // if there's a body, need to set the accepts header via requestContentType
3010 if (body && (this.type === 'POST' || this.type === 'PUT' || this.type === 'PATCH' || this.type === 'DELETE')) {
3011 if (this.opts.requestContentType)
3012 consumes = this.opts.requestContentType;
3014 // if any form params, content type must be set
3015 if (definedFormParams.length > 0) {
3016 if (definedFileParams.length > 0)
3017 consumes = 'multipart/form-data';
3019 consumes = 'application/x-www-form-urlencoded';
3021 else if (this.type === 'DELETE')
3023 else if (this.type != 'DELETE')
3027 if (consumes && this.operation.consumes) {
3028 if (this.operation.consumes.indexOf(consumes) === -1) {
3029 log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.operation.consumes));
3033 if (this.opts && this.opts.responseContentType) {
3034 accepts = this.opts.responseContentType;
3036 accepts = 'application/json';
3038 if (accepts && operation.produces) {
3039 if (operation.produces.indexOf(accepts) === -1) {
3040 log('server can\'t produce ' + accepts);
3044 if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded'))
3045 headers['Content-Type'] = consumes;
3047 headers.Accept = accepts;
3052 * SwaggerHttp is a wrapper for executing requests
3054 var SwaggerHttp = function() {};
3056 SwaggerHttp.prototype.execute = function(obj, opts) {
3057 if(obj && (typeof obj.useJQuery === 'boolean'))
3058 this.useJQuery = obj.useJQuery;
3060 this.useJQuery = this.isIE8();
3062 if(obj && typeof obj.body === 'object') {
3063 if(obj.body.type && obj.body.type !== 'formData')
3064 obj.body = JSON.stringify(obj.body);
3066 obj.contentType = false;
3067 obj.processData = false;
3068 // delete obj.cache;
3069 delete obj.headers['Content-Type'];
3074 return new JQueryHttpClient(opts).execute(obj);
3076 return new ShredHttpClient(opts).execute(obj);
3079 SwaggerHttp.prototype.isIE8 = function() {
3080 var detectedIE = false;
3081 if (typeof navigator !== 'undefined' && navigator.userAgent) {
3082 nav = navigator.userAgent.toLowerCase();
3083 if (nav.indexOf('msie') !== -1) {
3084 var version = parseInt(nav.split('msie')[1]);
3094 * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic.
3095 * NOTE: when jQuery is available it will export both '$' and 'jQuery' to the global space.
3096 * Since we are using closures here we need to alias it for internal use.
3098 var JQueryHttpClient = function(options) {
3101 var jQuery = window.jQuery;
3105 JQueryHttpClient.prototype.execute = function(obj) {
3109 obj.type = obj.method;
3111 delete obj.useJQuery;
3114 obj.beforeSend = function(xhr) {
3118 for (key in obj.headers) {
3119 if (key.toLowerCase() === "content-type") {
3120 results.push(obj.contentType = obj.headers[key]);
3121 } else if (key.toLowerCase() === "accept") {
3122 results.push(obj.accepts = obj.headers[key]);
3124 results.push(xhr.setRequestHeader(key, obj.headers[key]));
3131 obj.data = obj.body;
3133 obj.complete = function(response, textStatus, opts) {
3135 headerArray = response.getAllResponseHeaders().split("\n");
3137 for(var i = 0; i < headerArray.length; i++) {
3138 var toSplit = headerArray[i].trim();
3139 if(toSplit.length === 0)
3141 var separator = toSplit.indexOf(":");
3142 if(separator === -1) {
3143 // Name but no value in the header
3144 headers[toSplit] = null;
3147 var name = toSplit.substring(0, separator).trim(),
3148 value = toSplit.substring(separator + 1).trim();
3149 headers[name] = value;
3154 method: request.method,
3155 status: response.status,
3156 statusText: response.statusText,
3157 data: response.responseText,
3161 var contentType = (headers["content-type"]||headers["Content-Type"]||null);
3163 if(contentType.indexOf("application/json") === 0 || contentType.indexOf("+json") > 0) {
3165 out.obj = response.responseJSON || JSON.parse(out.data) || {};
3167 // do not set out.obj
3168 log("unable to parse JSON content");
3173 if(response.status >= 200 && response.status < 300)
3175 else if(response.status === 0 || (response.status >= 400 && response.status < 599))
3178 return cb.response(out);
3181 jQuery.support.cors = true;
3182 return jQuery.ajax(obj);
3186 * ShredHttpClient is a light-weight, node or browser HTTP client
3188 var ShredHttpClient = function(opts) {
3189 this.opts = (opts||{});
3190 this.isInitialized = false;
3192 var identity, toString;
3194 if (typeof window !== 'undefined') {
3195 this.Shred = require("./shred");
3196 this.content = require("./shred/content");
3199 this.Shred = require("shred");
3200 this.shred = new this.Shred(opts);
3203 ShredHttpClient.prototype.initShred = function () {
3204 this.isInitialized = true;
3205 this.registerProcessors(this.shred);
3208 ShredHttpClient.prototype.registerProcessors = function(shred) {
3209 var identity = function(x) {
3212 var toString = function(x) {
3213 return x.toString();
3216 if (typeof window !== 'undefined') {
3217 this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
3222 this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
3229 ShredHttpClient.prototype.execute = function(obj) {
3230 if(!this.isInitialized)
3233 var cb = obj.on, res;
3234 var transform = function(response) {
3236 headers: response._headers,
3237 url: response.request.url,
3238 method: response.request.method,
3239 status: response.status,
3240 data: response.content.data
3243 var headers = response._headers.normalized || response._headers;
3244 var contentType = (headers["content-type"]||headers["Content-Type"]||null);
3247 if(contentType.indexOf("application/json") === 0 || contentType.indexOf("+json") > 0) {
3248 if(response.content.data && response.content.data !== "")
3250 out.obj = JSON.parse(response.content.data);
3262 // Transform an error into a usable response-like object
3263 var transformError = function (error) {
3265 // Default to a status of 0 - The client will treat this as a generic permissions sort of error
3267 data: error.message || error
3273 if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
3274 // We can tell the client that this should be treated as a missing resource and not as a permissions thing
3282 error: function (response) {
3284 return cb.error(transform(response));
3286 // Catch the Shred error raised when the request errors as it is made (i.e. No Response is coming)
3287 request_error: function (err) {
3289 return cb.error(transformError(err));
3291 response: function (response) {
3293 return cb.response(transform(response));
3300 return this.shred.request(obj);
3304 var e = (typeof window !== 'undefined' ? window : exports);
3306 e.authorizations = authorizations = new SwaggerAuthorizations();
3307 e.ApiKeyAuthorization = ApiKeyAuthorization;
3308 e.PasswordAuthorization = PasswordAuthorization;
3309 e.CookieAuthorization = CookieAuthorization;
3310 e.SwaggerClient = SwaggerClient;
3311 e.SwaggerApi = SwaggerClient;
3312 e.Operation = Operation;
3314 e.addModel = addModel;
3315 e.Resolver = Resolver;