4 var __bind = function(fn, me){
6 return fn.apply(me, arguments);
11 log.history = log.history || [];
12 log.history.push(arguments);
14 console.log( Array.prototype.slice.call(arguments) );
18 if (!Array.prototype.indexOf) {
19 Array.prototype.indexOf = function(obj, start) {
20 for (var i = (start || 0), j = this.length; i < j; i++) {
21 if (this[i] === obj) { return i; }
27 if (!('filter' in Array.prototype)) {
28 Array.prototype.filter= function(filter, that /*opt*/) {
30 for (var i=0, n= this.length; i<n; i++)
31 if (i in this && filter.call(that, v= this[i], i, this))
37 if (!('map' in Array.prototype)) {
38 Array.prototype.map= function(mapper, that /*opt*/) {
39 var other= new Array(this.length);
40 for (var i= 0, n= this.length; i<n; i++)
42 other[i]= mapper.call(that, this[i], i, this);
47 Object.keys = Object.keys || (function () {
48 var hasOwnProperty = Object.prototype.hasOwnProperty,
49 hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
56 'propertyIsEnumerable',
59 DontEnumsLength = DontEnums.length;
62 if (typeof o != "object" && typeof o != "function" || o === null)
63 throw new TypeError("Object.keys called on a non-object");
67 if (hasOwnProperty.call(o, name))
72 for (var i = 0; i < DontEnumsLength; i++) {
73 if (hasOwnProperty.call(o, DontEnums[i]))
74 result.push(DontEnums[i]);
83 var SwaggerApi = function(url, options) {
87 this.authorizations = null;
88 this.authorizationScheme = null;
91 options = (options||{});
100 if (options.url != null)
101 this.url = options.url;
103 if (options.success != null)
104 this.success = options.success;
106 this.failure = options.failure != null ? options.failure : function() {};
107 this.progress = options.progress != null ? options.progress : function() {};
108 if (options.success != null)
112 SwaggerApi.prototype.build = function() {
114 this.progress('fetching resource list: ' + this.url);
116 useJQuery: this.useJQuery,
120 accept: "application/json"
123 error: function(response) {
124 if (_this.url.substring(0, 4) !== 'http') {
125 return _this.fail('Please specify the protocol for ' + _this.url);
126 } else if (response.status === 0) {
127 return _this.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.');
128 } else if (response.status === 404) {
129 return _this.fail('Can\'t read swagger JSON from ' + _this.url);
131 return _this.fail(response.status + ' : ' + response.statusText + ' ' + _this.url);
134 response: function(resp) {
135 var responseObj = resp.obj || JSON.parse(resp.data);
136 _this.swaggerVersion = responseObj.swaggerVersion;
137 if (_this.swaggerVersion === "1.2") {
138 return _this.buildFromSpec(responseObj);
140 return _this.buildFrom1_1Spec(responseObj);
145 var e = (typeof window !== 'undefined' ? window : exports);
146 e.authorizations.apply(obj);
147 new SwaggerHttp().execute(obj);
151 SwaggerApi.prototype.buildFromSpec = function(response) {
152 if (response.apiVersion != null) {
153 this.apiVersion = response.apiVersion;
157 this.produces = response.produces;
158 this.authSchemes = response.authorizations;
159 if (response.info != null) {
160 this.info = response.info;
164 for (i = 0; i < response.apis.length; i++) {
165 var api = response.apis[i];
166 if (api.operations) {
168 for (j = 0; j < api.operations.length; j++) {
169 operation = api.operations[j];
174 if (response.basePath) {
175 this.basePath = response.basePath;
176 } else if (this.url.indexOf('?') > 0) {
177 this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
179 this.basePath = this.url;
182 var newName = response.resourcePath.replace(/\//g, '');
183 this.resourcePath = response.resourcePath;
184 res = new SwaggerResource(response, this);
185 this.apis[newName] = res;
186 this.apisArray.push(res);
189 for (k = 0; k < response.apis.length; k++) {
190 var resource = response.apis[k];
191 res = new SwaggerResource(resource, this);
192 this.apis[res.name] = res;
193 this.apisArray.push(res);
202 SwaggerApi.prototype.buildFrom1_1Spec = function(response) {
203 log("This API is using a deprecated version of Swagger! Please see http://github.com/wordnik/swagger-core/wiki for more info");
204 if (response.apiVersion != null)
205 this.apiVersion = response.apiVersion;
208 this.produces = response.produces;
209 if (response.info != null) {
210 this.info = response.info;
213 for (var i = 0; i < response.apis.length; i++) {
214 var api = response.apis[i];
215 if (api.operations) {
216 for (var j = 0; j < api.operations.length; j++) {
217 operation = api.operations[j];
222 if (response.basePath) {
223 this.basePath = response.basePath;
224 } else if (this.url.indexOf('?') > 0) {
225 this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
227 this.basePath = this.url;
230 var newName = response.resourcePath.replace(/\//g, '');
231 this.resourcePath = response.resourcePath;
232 var res = new SwaggerResource(response, this);
233 this.apis[newName] = res;
234 this.apisArray.push(res);
236 for (k = 0; k < response.apis.length; k++) {
237 resource = response.apis[k];
238 res = new SwaggerResource(resource, this);
239 this.apis[res.name] = res;
240 this.apisArray.push(res);
249 SwaggerApi.prototype.selfReflect = function() {
250 var resource, resource_name, _ref;
251 if (this.apis == null) {
255 for (resource_name in _ref) {
256 resource = _ref[resource_name];
257 if (resource.ready == null) {
261 this.setConsolidatedModels();
263 if (this.success != null) {
264 return this.success();
268 SwaggerApi.prototype.fail = function(message) {
269 this.failure(message);
273 SwaggerApi.prototype.setConsolidatedModels = function() {
274 var model, modelName, resource, resource_name, _i, _len, _ref, _ref1, _results;
275 this.modelsArray = [];
278 for (resource_name in _ref) {
279 resource = _ref[resource_name];
280 for (modelName in resource.models) {
281 if (this.models[modelName] == null) {
282 this.models[modelName] = resource.models[modelName];
283 this.modelsArray.push(resource.models[modelName]);
287 _ref1 = this.modelsArray;
289 for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
291 _results.push(model.setReferencedModels(this.models));
296 SwaggerApi.prototype.help = function() {
297 var operation, operation_name, parameter, resource, resource_name, _i, _len, _ref, _ref1, _ref2;
299 for (resource_name in _ref) {
300 resource = _ref[resource_name];
302 _ref1 = resource.operations;
303 for (operation_name in _ref1) {
304 operation = _ref1[operation_name];
305 log(" " + operation.nickname);
306 _ref2 = operation.parameters;
307 for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
308 parameter = _ref2[_i];
309 log(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description);
316 var SwaggerResource = function(resourceObj, api) {
322 this.path = this.api.resourcePath != null ? this.api.resourcePath : resourceObj.path;
323 this.description = resourceObj.description;
325 var parts = this.path.split("/");
326 this.name = parts[parts.length - 1].replace('.{format}', '');
327 this.basePath = this.api.basePath;
328 this.operations = {};
329 this.operationsArray = [];
330 this.modelsArray = [];
333 this.useJQuery = (typeof api.useJQuery !== 'undefined' ? api.useJQuery : null);
335 if ((resourceObj.apis != null) && (this.api.resourcePath != null)) {
336 this.addApiDeclaration(resourceObj);
338 if (this.path == null) {
339 this.api.fail("SwaggerResources must have a path.");
341 if (this.path.substring(0, 4) === 'http') {
342 this.url = this.path.replace('{format}', 'json');
344 this.url = this.api.basePath + this.path.replace('{format}', 'json');
346 this.api.progress('fetching resource ' + this.name + ': ' + this.url);
350 useJQuery: this.useJQuery,
352 accept: "application/json"
355 response: function(resp) {
356 var responseObj = resp.obj || JSON.parse(resp.data);
357 return _this.addApiDeclaration(responseObj);
359 error: function(response) {
360 return _this.api.fail("Unable to read api '" +
361 _this.name + "' from path " + _this.url + " (server returned " + response.statusText + ")");
365 var e = typeof window !== 'undefined' ? window : exports;
366 e.authorizations.apply(obj);
367 new SwaggerHttp().execute(obj);
371 SwaggerResource.prototype.getAbsoluteBasePath = function(relativeBasePath) {
373 url = this.api.basePath;
374 pos = url.lastIndexOf(relativeBasePath);
376 parts = url.split("/");
377 url = parts[0] + "//" + parts[2];
378 if (relativeBasePath.indexOf("/") === 0) {
379 return url + relativeBasePath;
381 return url + "/" + relativeBasePath;
383 } else if (relativeBasePath === "/") {
384 return url.substring(0, pos);
386 return url.substring(0, pos) + relativeBasePath;
390 SwaggerResource.prototype.addApiDeclaration = function(response) {
391 if (response.produces != null)
392 this.produces = response.produces;
393 if (response.consumes != null)
394 this.consumes = response.consumes;
395 if ((response.basePath != null) && response.basePath.replace(/\s/g, '').length > 0)
396 this.basePath = response.basePath.indexOf("http") === -1 ? this.getAbsoluteBasePath(response.basePath) : response.basePath;
398 this.addModels(response.models);
400 for (var i = 0 ; i < response.apis.length; i++) {
401 var endpoint = response.apis[i];
402 this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces);
405 this.api[this.name] = this;
407 return this.api.selfReflect();
410 SwaggerResource.prototype.addModels = function(models) {
411 if (models != null) {
413 for (modelName in models) {
414 if (this.models[modelName] == null) {
415 var swaggerModel = new SwaggerModel(modelName, models[modelName]);
416 this.modelsArray.push(swaggerModel);
417 this.models[modelName] = swaggerModel;
418 this.rawModels[modelName] = models[modelName];
422 for (var i = 0; i < this.modelsArray.length; i++) {
423 model = this.modelsArray[i];
424 output.push(model.setReferencedModels(this.models));
430 SwaggerResource.prototype.addOperations = function(resource_path, ops, consumes, produces) {
433 for (var i = 0; i < ops.length; i++) {
435 consumes = this.consumes;
436 produces = this.produces;
437 if (o.consumes != null)
438 consumes = o.consumes;
440 consumes = this.consumes;
442 if (o.produces != null)
443 produces = o.produces;
445 produces = this.produces;
446 type = (o.type||o.responseClass);
448 if (type === "array") {
451 ref = o.items["type"] || o.items["$ref"];
452 type = "array[" + ref + "]";
454 responseMessages = o.responseMessages;
457 method = o.httpMethod;
459 if (o.supportedContentTypes) {
460 consumes = o.supportedContentTypes;
462 if (o.errorResponses) {
463 responseMessages = o.errorResponses;
464 for (var j = 0; j < responseMessages.length; j++) {
465 r = responseMessages[j];
466 r.message = r.reason;
470 o.nickname = this.sanitize(o.nickname);
471 op = new SwaggerOperation(o.nickname, resource_path, method, o.parameters, o.summary, o.notes, type, responseMessages, this, consumes, produces, o.authorizations);
472 this.operations[op.nickname] = op;
473 output.push(this.operationsArray.push(op));
479 SwaggerResource.prototype.sanitize = function(nickname) {
481 op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|./?,\\'""-]/g, '_');
483 op = op.replace(/((_){2,})/g, '_');
484 op = op.replace(/^(_)*/g, '');
485 op = op.replace(/([_])*$/g, '');
489 SwaggerResource.prototype.help = function() {
490 var op = this.operations;
493 for (operation_name in op) {
494 operation = op[operation_name];
495 var msg = " " + operation.nickname;
496 for (var i = 0; i < operation.parameters; i++) {
497 parameter = operation.parameters[i];
498 msg.concat(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description);
505 var SwaggerModel = function(modelName, obj) {
506 this.name = obj.id != null ? obj.id : modelName;
507 this.properties = [];
509 for (propertyName in obj.properties) {
510 if (obj.required != null) {
512 for (value in obj.required) {
513 if (propertyName === obj.required[value]) {
514 obj.properties[propertyName].required = true;
518 prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName]);
519 this.properties.push(prop);
523 SwaggerModel.prototype.setReferencedModels = function(allModels) {
525 for (var i = 0; i < this.properties.length; i++) {
526 var property = this.properties[i];
527 var type = property.type || property.dataType;
528 if (allModels[type] != null)
529 results.push(property.refModel = allModels[type]);
530 else if ((property.refDataType != null) && (allModels[property.refDataType] != null))
531 results.push(property.refModel = allModels[property.refDataType]);
533 results.push(void 0);
538 SwaggerModel.prototype.getMockSignature = function(modelsToIgnore) {
539 var propertiesStr = [];
540 for (var i = 0; i < this.properties.length; i++) {
541 prop = this.properties[i];
542 propertiesStr.push(prop.toString());
545 var strong = '<span class="strong">';
546 var stronger = '<span class="stronger">';
547 var strongClose = '</span>';
548 var classOpen = strong + this.name + ' {' + strongClose;
549 var classClose = strong + '}' + strongClose;
550 var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
553 modelsToIgnore.push(this.name);
555 for (var i = 0; i < this.properties.length; i++) {
556 prop = this.properties[i];
557 if ((prop.refModel != null) && modelsToIgnore.indexOf(prop.refModel.name) === -1) {
558 returnVal = returnVal + ('<br>' + prop.refModel.getMockSignature(modelsToIgnore));
564 SwaggerModel.prototype.createJSONSample = function(modelsToIgnore) {
566 var modelsToIgnore = (modelsToIgnore||[])
567 modelsToIgnore.push(this.name);
568 for (var i = 0; i < this.properties.length; i++) {
569 prop = this.properties[i];
570 result[prop.name] = prop.getSampleValue(modelsToIgnore);
572 modelsToIgnore.pop(this.name);
576 var SwaggerModelProperty = function(name, obj) {
578 this.dataType = obj.type || obj.dataType || obj["$ref"];
579 this.isCollection = this.dataType && (this.dataType.toLowerCase() === 'array' || this.dataType.toLowerCase() === 'list' || this.dataType.toLowerCase() === 'set');
580 this.descr = obj.description;
581 this.required = obj.required;
582 if (obj.items != null) {
583 if (obj.items.type != null) {
584 this.refDataType = obj.items.type;
586 if (obj.items.$ref != null) {
587 this.refDataType = obj.items.$ref;
590 this.dataTypeWithRef = this.refDataType != null ? (this.dataType + '[' + this.refDataType + ']') : this.dataType;
591 if (obj.allowableValues != null) {
592 this.valueType = obj.allowableValues.valueType;
593 this.values = obj.allowableValues.values;
594 if (this.values != null) {
595 this.valuesString = "'" + this.values.join("' or '") + "'";
598 if (obj["enum"] != null) {
599 this.valueType = "string";
600 this.values = obj["enum"];
601 if (this.values != null) {
602 this.valueString = "'" + this.values.join("' or '") + "'";
607 SwaggerModelProperty.prototype.getSampleValue = function(modelsToIgnore) {
609 if ((this.refModel != null) && (modelsToIgnore.indexOf(prop.refModel.name) === -1)) {
610 result = this.refModel.createJSONSample(modelsToIgnore);
612 if (this.isCollection) {
613 result = this.toSampleValue(this.refDataType);
615 result = this.toSampleValue(this.dataType);
618 if (this.isCollection) {
625 SwaggerModelProperty.prototype.toSampleValue = function(value) {
627 if (value === "integer") {
629 } else if (value === "boolean") {
631 } else if (value === "double" || value === "number") {
633 } else if (value === "string") {
641 SwaggerModelProperty.prototype.toString = function() {
642 var req = this.required ? 'propReq' : 'propOpt';
643 var str = '<span class="propName ' + req + '">' + this.name + '</span> (<span class="propType">' + this.dataTypeWithRef + '</span>';
644 if (!this.required) {
645 str += ', <span class="propOptKey">optional</span>';
648 if (this.values != null) {
649 str += " = <span class='propVals'>['" + this.values.join("' or '") + "']</span>";
651 if (this.descr != null) {
652 str += ': <span class="propDesc">' + this.descr + '</span>';
657 var SwaggerOperation = function(nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations) {
661 this.nickname = (nickname||errors.push("SwaggerOperations must have a nickname."));
662 this.path = (path||errors.push("SwaggerOperation " + nickname + " is missing path."));
663 this.method = (method||errors.push("SwaggerOperation " + nickname + " is missing method."));
664 this.parameters = parameters != null ? parameters : [];
665 this.summary = summary;
668 this.responseMessages = (responseMessages||[]);
669 this.resource = (resource||errors.push("Resource is required"));
670 this.consumes = consumes;
671 this.produces = produces;
672 this.authorizations = authorizations;
673 this["do"] = __bind(this["do"], this);
675 if (errors.length > 0)
676 this.resource.api.fail(errors);
678 this.path = this.path.replace('{format}', 'json');
679 this.method = this.method.toLowerCase();
680 this.isGetMethod = this.method === "get";
682 this.resourceName = this.resource.name;
683 if(typeof this.type !== 'undefined' && this.type === 'void')
686 this.responseClassSignature = this.getSignature(this.type, this.resource.models);
687 this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models);
690 for(var i = 0; i < this.parameters.length; i ++) {
691 var param = this.parameters[i];
692 // might take this away
693 param.name = param.name || param.type || param.dataType;
695 // for 1.1 compatibility
696 var type = param.type || param.dataType;
697 if(type === 'array') {
698 type = 'array[' + (param.items.$ref ? param.items.$ref : param.items.type) + ']';
702 if(type.toLowerCase() === 'boolean') {
703 param.allowableValues = {};
704 param.allowableValues.values = ["true", "false"];
706 param.signature = this.getSignature(type, this.resource.models);
707 param.sampleJSON = this.getSampleJSON(type, this.resource.models);
709 var enumValue = param["enum"];
710 if(enumValue != null) {
712 param.allowableValues = {};
713 param.allowableValues.descriptiveValues = [];
715 for(var j = 0; j < enumValue.length; j++) {
716 var v = enumValue[j];
717 if(param.defaultValue != null) {
718 param.allowableValues.descriptiveValues.push ({
720 isDefault: (v === param.defaultValue)
724 param.allowableValues.descriptiveValues.push ({
731 else if(param.allowableValues != null) {
732 if(param.allowableValues.valueType === "RANGE")
733 param.isRange = true;
736 if(param.allowableValues != null) {
737 param.allowableValues.descriptiveValues = [];
738 if(param.allowableValues.values) {
739 for(var j = 0; j < param.allowableValues.values.length; j++){
740 var v = param.allowableValues.values[j];
741 if(param.defaultValue != null) {
742 param.allowableValues.descriptiveValues.push ({
744 isDefault: (v === param.defaultValue)
748 param.allowableValues.descriptiveValues.push ({
758 this.resource[this.nickname] = function(args, callback, error) {
759 return _this["do"](args, callback, error);
761 this.resource[this.nickname].help = function() {
766 SwaggerOperation.prototype.isListType = function(type) {
767 if (type && type.indexOf('[') >= 0) {
768 return type.substring(type.indexOf('[') + 1, type.indexOf(']'));
774 SwaggerOperation.prototype.getSignature = function(type, models) {
775 var isPrimitive, listType;
776 listType = this.isListType(type);
777 isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
781 if (listType != null) {
782 return models[listType].getMockSignature();
784 return models[type].getMockSignature();
789 SwaggerOperation.prototype.getSampleJSON = function(type, models) {
790 var isPrimitive, listType, val;
791 listType = this.isListType(type);
792 isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
793 val = isPrimitive ? void 0 : (listType != null ? models[listType].createJSONSample() : models[type].createJSONSample());
795 val = listType ? [val] : val;
796 return JSON.stringify(val, null, 2);
800 SwaggerOperation.prototype["do"] = function(args, opts, callback, error) {
801 var key, param, params, possibleParams, req, requestContentType, responseContentType, value, _i, _len, _ref;
808 requestContentType = null;
809 responseContentType = null;
810 if ((typeof args) === "function") {
815 if ((typeof opts) === "function") {
820 error = function(xhr, textStatus, error) {
821 return log(xhr, textStatus, error);
824 if (callback == null) {
825 callback = function(response) {
828 if (response != null) {
829 content = response.data;
833 return log("default callback: " + content);
838 if (args.headers != null) {
839 params.headers = args.headers;
843 var possibleParams = [];
844 for(var i = 0; i < this.parameters.length; i++) {
845 var param = this.parameters[i];
846 if(param.paramType === 'header') {
848 params.headers[param.name] = args[param.name];
850 else if(param.paramType === 'form' || param.paramType.toLowerCase() === 'file')
851 possibleParams.push(param);
854 if (args.body != null) {
855 params.body = args.body;
859 if (possibleParams) {
861 for (key in possibleParams) {
862 value = possibleParams[key];
863 if (args[value.name]) {
864 params[value.name] = args[value.name];
869 req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this);
870 if (opts.mock != null) {
877 SwaggerOperation.prototype.pathJson = function() {
878 return this.path.replace("{format}", "json");
881 SwaggerOperation.prototype.pathXml = function() {
882 return this.path.replace("{format}", "xml");
885 SwaggerOperation.prototype.encodePathParam = function(pathParam) {
886 var encParts, part, parts, _i, _len;
887 if (pathParam.indexOf("/") === -1) {
888 return encodeURIComponent(pathParam);
890 parts = pathParam.split("/");
892 for (_i = 0, _len = parts.length; _i < _len; _i++) {
894 encParts.push(encodeURIComponent(part));
896 return encParts.join("/");
900 SwaggerOperation.prototype.urlify = function(args) {
901 var url = this.resource.basePath + this.pathJson();
902 var params = this.parameters;
903 for(var i = 0; i < params.length; i ++){
904 var param = params[i];
905 if (param.paramType === 'path') {
906 if(args[param.name]) {
907 // apply path params and remove from args
908 var reg = new RegExp('\{' + param.name + '[^\}]*\}', 'gi');
909 url = url.replace(reg, this.encodePathParam(args[param.name]));
910 delete args[param.name];
913 throw "" + param.name + " is a required path param.";
917 var queryParams = "";
918 for(var i = 0; i < params.length; i ++){
919 var param = params[i];
920 if(param.paramType === 'query') {
921 if (args[param.name] !== undefined) {
922 if (queryParams !== '')
924 queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]);
928 if ((queryParams != null) && queryParams.length > 0)
929 url += '?' + queryParams;
933 SwaggerOperation.prototype.supportHeaderParams = function() {
934 return this.resource.api.supportHeaderParams;
937 SwaggerOperation.prototype.supportedSubmitMethods = function() {
938 return this.resource.api.supportedSubmitMethods;
941 SwaggerOperation.prototype.getQueryParams = function(args) {
942 return this.getMatchingParams(['query'], args);
945 SwaggerOperation.prototype.getHeaderParams = function(args) {
946 return this.getMatchingParams(['header'], args);
949 SwaggerOperation.prototype.getMatchingParams = function(paramTypes, args) {
950 var matchingParams = {};
951 var params = this.parameters;
952 for (var i = 0; i < params.length; i++) {
954 if (args && args[param.name])
955 matchingParams[param.name] = args[param.name];
957 var headers = this.resource.api.headers;
959 for (name in headers) {
960 var value = headers[name];
961 matchingParams[name] = value;
963 return matchingParams;
966 SwaggerOperation.prototype.help = function() {
968 var params = this.parameters;
969 for (var i = 0; i < params.length; i++) {
970 var param = params[i];
973 msg += "* " + param.name + (param.required ? ' (required)' : '') + " - " + param.description;
978 var SwaggerRequest = function(type, url, params, opts, successCallback, errorCallback, operation, execution) {
981 this.useJQuery = (typeof operation.useJQuery !== 'undefined' ? operation.useJQuery : null);
982 this.type = (type||errors.push("SwaggerRequest type is required (get/post/put/delete/patch/options)."));
983 this.url = (url||errors.push("SwaggerRequest url is required."));
984 this.params = params;
986 this.successCallback = (successCallback||errors.push("SwaggerRequest successCallback is required."));
987 this.errorCallback = (errorCallback||errors.push("SwaggerRequest error callback is required."));
988 this.operation = (operation||errors.push("SwaggerRequest operation is required."));
989 this.execution = execution;
990 this.headers = (params.headers||{});
992 if(errors.length > 0) {
996 this.type = this.type.toUpperCase();
999 var body = params.body;
1000 var parent = params["parent"];
1001 var requestContentType = "application/json";
1003 var formParams = [];
1004 var fileParams = [];
1005 var params = this.operation.parameters;
1008 for(var i = 0; i < params.length; i++) {
1009 var param = params[i];
1010 if(param.paramType === "form")
1011 formParams.push(param);
1012 else if(param.paramType === "file")
1013 fileParams.push(param);
1017 if (body && (this.type === "POST" || this.type === "PUT" || this.type === "PATCH")) {
1018 if (this.opts.requestContentType) {
1019 requestContentType = this.opts.requestContentType;
1022 // if any form params, content type must be set
1023 if(formParams.length > 0) {
1024 if(fileParams.length > 0)
1025 requestContentType = "multipart/form-data";
1027 requestContentType = "application/x-www-form-urlencoded";
1029 else if (this.type != "DELETE")
1030 requestContentType = null;
1033 if (requestContentType && this.operation.consumes) {
1034 if (this.operation.consumes[requestContentType] === 'undefined') {
1035 log("server doesn't consume " + requestContentType + ", try " + JSON.stringify(this.operation.consumes));
1036 if (this.requestContentType === null) {
1037 requestContentType = this.operation.consumes[0];
1042 var responseContentType = null;
1043 if (this.opts.responseContentType) {
1044 responseContentType = this.opts.responseContentType;
1046 responseContentType = "application/json";
1048 if (responseContentType && this.operation.produces) {
1049 if (this.operation.produces[responseContentType] === 'undefined') {
1050 log("server can't produce " + responseContentType);
1053 if (requestContentType && requestContentType.indexOf("application/x-www-form-urlencoded") === 0) {
1055 var possibleParams = {};
1058 for(key in formParams){
1059 var param = formParams[key];
1060 values[param.name] = param;
1065 for(key in values) {
1066 value = this.params[key];
1067 if(typeof value !== 'undefined'){
1070 encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
1076 for (name in this.headers)
1077 myHeaders[name] = this.headers[name];
1078 if ((requestContentType && body !== "") || (requestContentType === "application/x-www-form-urlencoded"))
1079 myHeaders["Content-Type"] = requestContentType;
1080 if (responseContentType)
1081 myHeaders["Accept"] = responseContentType;
1083 if (!((this.headers != null) && (this.headers.mock != null))) {
1089 useJQuery: this.useJQuery,
1091 error: function(response) {
1092 return _this.errorCallback(response, _this.opts.parent);
1094 redirect: function(response) {
1095 return _this.successCallback(response, _this.opts.parent);
1097 307: function(response) {
1098 return _this.successCallback(response, _this.opts.parent);
1100 response: function(response) {
1101 return _this.successCallback(response, _this.opts.parent);
1106 if (typeof window !== 'undefined') {
1111 status = e.authorizations.apply(obj, this.operation.authorizations);
1112 if (opts.mock == null) {
1113 if (status !== false) {
1114 new SwaggerHttp().execute(obj);
1116 obj.canceled = true;
1124 SwaggerRequest.prototype.asCurl = function() {
1128 for(key in this.headers) {
1129 results.push("--header \"" + key + ": " + this.headers[v] + "\"");
1132 return "curl " + (results.join(" ")) + " " + this.url;
1136 * SwaggerHttp is a wrapper for executing requests
1138 var SwaggerHttp = function() {};
1140 SwaggerHttp.prototype.execute = function(obj) {
1141 if(obj && (typeof obj.useJQuery === 'boolean'))
1142 this.useJQuery = obj.useJQuery;
1144 this.useJQuery = this.isIE8();
1147 return new JQueryHttpClient().execute(obj);
1149 return new ShredHttpClient().execute(obj);
1152 SwaggerHttp.prototype.isIE8 = function() {
1153 var detectedIE = false;
1154 if (typeof navigator !== 'undefined' && navigator.userAgent) {
1155 nav = navigator.userAgent.toLowerCase();
1156 if (nav.indexOf('msie') !== -1) {
1157 var version = parseInt(nav.split('msie')[1]);
1167 * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic
1169 var JQueryHttpClient = function(options) {}
1171 JQueryHttpClient.prototype.execute = function(obj) {
1175 obj.type = obj.method;
1178 obj.beforeSend = function(xhr) {
1183 for (key in obj.headers) {
1184 if (key.toLowerCase() === "content-type") {
1185 results.push(obj.contentType = obj.headers[key]);
1186 } else if (key.toLowerCase() === "accept") {
1187 results.push(obj.accepts = obj.headers[key]);
1189 results.push(xhr.setRequestHeader(key, obj.headers[key]));
1196 obj.data = obj.body;
1197 obj.complete = function(response, textStatus, opts) {
1199 headerArray = response.getAllResponseHeaders().split(":");
1201 for(var i = 0; i < headerArray.length / 2; i++)
1202 headers[headerArray[i] = headerArray[i+1]];
1207 method: request.method,
1208 status: response.status,
1209 data: response.responseText,
1213 var contentType = (headers["content-type"]||headers["Content-Type"]||null)
1215 if(contentType != null) {
1216 if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
1217 if(response.responseText && response.responseText !== "")
1218 out.obj = JSON.parse(response.responseText);
1224 if(response.status >= 200 && response.status < 300)
1226 else if(response.status === 0 || (response.status >= 400 && response.status < 599))
1229 return cb.response(out);
1232 $.support.cors = true;
1237 * ShredHttpClient is a light-weight, node or browser HTTP client
1239 var ShredHttpClient = function(options) {
1240 this.options = (options||{});
1241 this.isInitialized = false;
1243 var identity, toString;
1245 if (typeof window !== 'undefined') {
1246 this.Shred = require("./shred");
1247 this.content = require("./shred/content");
1250 this.Shred = require("shred");
1251 this.shred = new this.Shred();
1254 ShredHttpClient.prototype.initShred = function () {
1255 this.isInitialized = true;
1256 this.registerProcessors(this.shred);
1259 ShredHttpClient.prototype.registerProcessors = function(shred) {
1260 var identity = function(x) {
1263 var toString = function(x) {
1264 return x.toString();
1267 if (typeof window !== 'undefined') {
1268 this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
1273 this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
1280 ShredHttpClient.prototype.execute = function(obj) {
1281 if(!this.isInitialized)
1284 var cb = obj.on, res;
1286 var transform = function(response) {
1288 headers: response._headers,
1289 url: response.request.url,
1290 method: response.request.method,
1291 status: response.status,
1292 data: response.content.data
1295 var contentType = (response._headers["content-type"]||response._headers["Content-Type"]||null)
1297 if(contentType != null) {
1298 if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
1299 if(response.content.data && response.content.data !== "")
1300 out.obj = JSON.parse(response.content.data);
1309 error: function(response) {
1311 return cb.error(transform(response));
1313 redirect: function(response) {
1315 return cb.redirect(transform(response));
1317 307: function(response) {
1319 return cb.redirect(transform(response));
1321 response: function(response) {
1323 return cb.response(transform(response));
1329 return this.shred.request(obj);
1333 * SwaggerAuthorizations applys the correct authorization to an operation being executed
1335 var SwaggerAuthorizations = function() {
1339 SwaggerAuthorizations.prototype.add = function(name, auth) {
1340 this.authz[name] = auth;
1344 SwaggerAuthorizations.prototype.remove = function(name) {
1345 return delete this.authz[name];
1348 SwaggerAuthorizations.prototype.apply = function(obj, authorizations) {
1351 for (key in this.authz) {
1352 value = this.authz[key];
1353 result = value.apply(obj, authorizations);
1354 if (result === false)
1356 if (result === true)
1363 * ApiKeyAuthorization allows a query param or header to be injected
1365 var ApiKeyAuthorization = function(name, value, type) {
1371 ApiKeyAuthorization.prototype.apply = function(obj, authorizations) {
1372 if (this.type === "query") {
1373 if (obj.url.indexOf('?') > 0)
1374 obj.url = obj.url + "&" + this.name + "=" + this.value;
1376 obj.url = obj.url + "?" + this.name + "=" + this.value;
1378 } else if (this.type === "header") {
1379 obj.headers[this.name] = this.value;
1385 * Password Authorization is a basic auth implementation
1387 var PasswordAuthorization = function(name, username, password) {
1389 this.username = username;
1390 this.password = password;
1392 if (typeof window !== 'undefined')
1395 this._btoa = require("btoa");
1398 PasswordAuthorization.prototype.apply = function(obj, authorizations) {
1399 var base64encoder = this._btoa;
1400 obj.headers["Authorization"] = "Basic " + base64encoder(this.username + ":" + this.password);
1404 var e = (typeof window !== 'undefined' ? window : exports);
1406 e.SwaggerHttp = SwaggerHttp;
1407 e.SwaggerRequest = SwaggerRequest;
1408 e.authorizations = new SwaggerAuthorizations();
1409 e.ApiKeyAuthorization = ApiKeyAuthorization;
1410 e.PasswordAuthorization = PasswordAuthorization;
1411 e.JQueryHttpClient = JQueryHttpClient;
1412 e.ShredHttpClient = ShredHttpClient;
1413 e.SwaggerOperation = SwaggerOperation;
1414 e.SwaggerModel = SwaggerModel;
1415 e.SwaggerModelProperty = SwaggerModelProperty;
1416 e.SwaggerResource = SwaggerResource;
1417 e.SwaggerApi = SwaggerApi;