diff --git a/dist/lib/swagger-client.js b/dist/lib/swagger-client.js index cd40c01c..cb917cb7 100644 --- a/dist/lib/swagger-client.js +++ b/dist/lib/swagger-client.js @@ -1,8 +1,9 @@ -// swagger-client.js -// version 2.1.0-alpha.5 /** - * Array Model - **/ + * swagger-client - swagger.js is a javascript client for use with swaggering APIs. + * @version v2.1.0-alpha.5 + * @link http://swagger.io + * @license apache 2.0 + */ var ArrayModel = function(definition) { this.name = "name"; this.definition = definition || {}; @@ -57,6 +58,7 @@ ArrayModel.prototype.getMockSignature = function(modelsToIgnore) { } }; + /** * SwaggerAuthorizations applys the correct authorization to an operation being executed */ @@ -157,7 +159,8 @@ PasswordAuthorization.prototype.apply = function(obj, authorizations) { var base64encoder = this._btoa; obj.headers["Authorization"] = "Basic " + base64encoder(this.username + ":" + this.password); return true; -};var __bind = function(fn, me){ +}; +var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; @@ -238,6 +241,7 @@ Object.keys = Object.keys || (function () { return result; }; })(); + /** * PrimitiveModel **/ @@ -289,7 +293,8 @@ PrimitiveModel.prototype.getMockSignature = function(modelsToIgnore) { } } return returnVal; -};var SwaggerClient = function(url, options) { +}; +var SwaggerClient = function(url, options) { this.isBuilt = false; this.url = null; this.debug = false; @@ -316,6 +321,7 @@ PrimitiveModel.prototype.getMockSignature = function(modelsToIgnore) { if (typeof options.useJQuery === 'boolean') this.useJQuery = options.useJQuery; + this.supportedSubmitMethods = options.supportedSubmitMethods || []; this.failure = options.failure != null ? options.failure : function() {}; this.progress = options.progress != null ? options.progress : function() {}; this.spec = options.spec; @@ -763,7 +769,7 @@ Operation.prototype.supportHeaderParams = function () { }; Operation.prototype.supportedSubmitMethods = function () { - return this.resource.api.supportedSubmitMethods; + return this.parent.supportedSubmitMethods; }; Operation.prototype.getHeaderParams = function (args) { @@ -1111,11 +1117,8 @@ Operation.prototype.encodeQueryCollection = function(type, name, value) { return encoded; } -/** - * TODO this encoding needs to be changed - **/ Operation.prototype.encodeQueryParam = function(arg) { - return escape(arg); + return encodeURIComponent(arg); } /** @@ -1378,6 +1381,7 @@ e.PasswordAuthorization = PasswordAuthorization; e.CookieAuthorization = CookieAuthorization; e.SwaggerClient = SwaggerClient; e.Operation = Operation; + /** * SwaggerHttp is a wrapper for executing requests */ @@ -1389,6 +1393,10 @@ SwaggerHttp.prototype.execute = function(obj) { else this.useJQuery = this.isIE8(); + if(obj && typeof obj.body === 'object') { + obj.body = JSON.stringify(obj.body); + } + if(this.useJQuery) return new JQueryHttpClient().execute(obj); else @@ -1563,7 +1571,8 @@ ShredHttpClient.prototype.execute = function(obj) { data: response.content.data }; - var contentType = (response._headers["content-type"]||response._headers["Content-Type"]||null) + var headers = response._headers.normalized || response._headers; + var contentType = (headers["content-type"]||headers["Content-Type"]||null) if(contentType != null) { if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) { diff --git a/dist/swagger-ui.js b/dist/swagger-ui.js index b052b435..d17f53ec 100644 --- a/dist/swagger-ui.js +++ b/dist/swagger-ui.js @@ -271,7 +271,7 @@ function program1(depth0,data) { stack2 = ((stack1 = ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.description)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n "; - stack2 = helpers['if'].call(depth0, ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.termsOfServiceUrl), {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data}); + stack2 = helpers['if'].call(depth0, ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.termsOfService), {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data}); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n "; stack2 = helpers['if'].call(depth0, ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.contact), {hash:{},inverse:self.noop,fn:self.program(4, program4, data),data:data}); @@ -286,7 +286,7 @@ function program2(depth0,data) { var buffer = "", stack1; buffer += "
"; return buffer; } @@ -1785,7 +1785,7 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; OperationView.prototype.render = function() { var a, auth, auths, code, contentTypeModel, isMethodSubmissionSupported, k, key, o, param, ref, responseContentTypeView, responseSignatureView, schema, schemaObj, signatureModel, statusCode, type, v, value, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _m, _ref10, _ref11, _ref5, _ref6, _ref7, _ref8, _ref9; - isMethodSubmissionSupported = true; + isMethodSubmissionSupported = jQuery.inArray(this.model.method, this.model.supportedSubmitMethods()) >= 0; if (!isMethodSubmissionSupported) { this.model.isReadOnly = true; } diff --git a/dist/swagger-ui.min.js b/dist/swagger-ui.min.js index 330262f1..45c147b3 100644 --- a/dist/swagger-ui.min.js +++ b/dist/swagger-ui.min.js @@ -1 +1 @@ -$(function(){$.fn.vAlign=function(){return this.each(function(c){var a=$(this).height();var d=$(this).parent().height();var b=(d-a)/2;$(this).css("margin-top",b)})};$.fn.stretchFormtasticInputWidthToParent=function(){return this.each(function(b){var d=$(this).closest("form").innerWidth();var c=parseInt($(this).closest("form").css("padding-left"),10)+parseInt($(this).closest("form").css("padding-right"),10);var a=parseInt($(this).css("padding-left"),10)+parseInt($(this).css("padding-right"),10);$(this).css("width",d-c-a)})};$("form.formtastic li.string input, form.formtastic textarea").stretchFormtasticInputWidthToParent();$("ul.downplayed li div.content p").vAlign();$("form.sandbox").submit(function(){var a=true;$(this).find("input.required").each(function(){$(this).removeClass("error");if($(this).val()==""){$(this).addClass("error");$(this).wiggle();a=false}});return a})});function clippyCopiedCallback(b){$("#api_key_copied").fadeIn().delay(1000).fadeOut()}log=function(){log.history=log.history||[];log.history.push(arguments);if(this.console){console.log(Array.prototype.slice.call(arguments)[0])}};if(Function.prototype.bind&&console&&typeof console.log=="object"){["log","info","warn","error","assert","dir","clear","profile","profileEnd"].forEach(function(a){console[a]=this.bind(console[a],console)},Function.prototype.call)}var Docs={shebang:function(){var b=$.param.fragment().split("/");b.shift();switch(b.length){case 1:var d="resource_"+b[0];Docs.expandEndpointListForResource(b[0]);$("#"+d).slideto({highlight:false});break;case 2:Docs.expandEndpointListForResource(b[0]);$("#"+d).slideto({highlight:false});var c=b.join("_");var a=c+"_content";Docs.expandOperation($("#"+a));$("#"+c).slideto({highlight:false});break}},toggleEndpointListForResource:function(b){var a=$("li#resource_"+Docs.escapeResourceName(b)+" ul.endpoints");if(a.is(":visible")){Docs.collapseEndpointListForResource(b)}else{Docs.expandEndpointListForResource(b)}},expandEndpointListForResource:function(b){var b=Docs.escapeResourceName(b);if(b==""){$(".resource ul.endpoints").slideDown();return}$("li#resource_"+b).addClass("active");var a=$("li#resource_"+b+" ul.endpoints");a.slideDown()},collapseEndpointListForResource:function(b){var b=Docs.escapeResourceName(b);$("li#resource_"+b).removeClass("active");var a=$("li#resource_"+b+" ul.endpoints");a.slideUp()},expandOperationsForResource:function(a){Docs.expandEndpointListForResource(a);if(a==""){$(".resource ul.endpoints li.operation div.content").slideDown();return}$("li#resource_"+Docs.escapeResourceName(a)+" li.operation div.content").each(function(){Docs.expandOperation($(this))})},collapseOperationsForResource:function(a){Docs.expandEndpointListForResource(a);$("li#resource_"+Docs.escapeResourceName(a)+" li.operation div.content").each(function(){Docs.collapseOperation($(this))})},escapeResourceName:function(a){return a.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g,"\\$&")},expandOperation:function(a){a.slideDown()},collapseOperation:function(a){a.slideUp()}};(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.apikey_button_view=b(function(e,k,d,j,i){this.compilerInfo=[4,">= 1.0.0"];d=this.merge(d,e.helpers);i=i||{};var g="",c,f="function",h=this.escapeExpression;g+="\n";if(C=s.description){C=C.call(E,{hash:{},data:D})}else{C=E.description;C=typeof C===e?C.apply(E):C}if(C||C===0){B+=C}B+="
\n ";return B}function m(C,B){return'\n\n
| Parameter | \nValue | \nDescription | \nParameter Type | \nData Type | \n
|---|
| HTTP Status Code | \nReason | \nResponse Model | \n
|---|
';if(c=d.sampleJSON){c=c.call(k,{hash:{},data:i})}else{c=k.sampleJSON;c=typeof c===f?c.apply(k):c}g+=h(c)+'\n \n ").text(Q);I=$('').append(G)}else{if(P==="application/xml"||/\+xml$/.test(P)){G=$("").text(this.formatXml(N));I=$('').append(G)}else{if(P==="text/html"){G=$("").html(_.escape(N));I=$('').append(G)}else{if(/^image\//.test(P)){I=$("").text(N);I=$('').append(G)}}}}}L=I;$(".request_url",$(this.el)).html("");$(".request_url pre",$(this.el)).text(F);$(".response_code",$(this.el)).html(""+J.status+"");$(".response_body",$(this.el)).html(L);$(".response_headers",$(this.el)).html("
"+_.escape(JSON.stringify(J.headers,null," ")).replace(/\n/g,"");$(".response",$(this.el)).slideDown();$(".response_hider",$(this.el)).show();$(".response_throbber",$(this.el)).hide();K=$(".response_body",$(this.el))[0];E=this.options.swaggerOptions;if(E.highlightSizeThreshold&&J.data.length>E.highlightSizeThreshold){return K}else{return hljs.highlightBlock(K)}};C.prototype.toggleOperationContent=function(){var E;E=$("#"+Docs.escapeResourceName(this.model.parentId+"_"+this.model.nickname+"_content"));if(E.is(":visible")){return Docs.collapseOperation(E)}else{return Docs.expandOperation(E)}};return C})(Backbone.View);r=(function(D){y(C,D);function C(){e=C.__super__.constructor.apply(this,arguments);return e}C.prototype.initialize=function(){};C.prototype.render=function(){var F,E,G;G=this.template();$(this.el).html(G(this.model));if(swaggerUi.api.models.hasOwnProperty(this.model.responseModel)){F={sampleJSON:JSON.stringify(swaggerUi.api.models[this.model.responseModel].createJSONSample(),null,2),isParam:false,signature:swaggerUi.api.models[this.model.responseModel].getMockSignature()};E=new j({model:F,tagName:"div"});$(".model-signature",this.$el).append(E.render().el)}else{$(".model-signature",this.$el).html("")}return this};C.prototype.template=function(){return Handlebars.templates.status_code};return C})(Backbone.View);m=(function(D){y(C,D);function C(){c=C.__super__.constructor.apply(this,arguments);return c}C.prototype.initialize=function(){return Handlebars.registerHelper("isArray",function(F,E){if(F.type.toLowerCase()==="array"||F.allowMultiple){return E.fn(this)}else{return E.inverse(this)}})};C.prototype.render=function(){var E,F,I,G,J,H,M,N,L,K;K=this.model.type||this.model.dataType;if(typeof K==="undefined"){H=this.model.schema;if(H&&H["$ref"]){G=H["$ref"];if(G.indexOf("#/definitions/")===0){K=G.substring("#/definitions/".length)}else{K=G}}}this.model.type=K;this.model.paramType=this.model["in"]||this.model.paramType;if(this.model.paramType==="body"){this.model.isBody=true}if(K&&K.toLowerCase()==="file"){this.model.isFile=true}this.model["default"]=this.model["default"]||this.model.defaultValue;if(this.model.allowableValues){this.model.isList=true}L=this.template();$(this.el).html(L(this.model));M={sampleJSON:this.model.sampleJSON,isParam:true,signature:this.model.signature};if(this.model.sampleJSON){N=new j({model:M,tagName:"div"});$(".model-signature",$(this.el)).append(N.render().el)}else{$(".model-signature",$(this.el)).html(this.model.signature)}F=false;if(this.model.isBody){F=true}E={isParam:F};E.consumes=this.model.consumes;if(F){I=new n({model:E});$(".parameter-content-type",$(this.el)).append(I.render().el)}else{J=new o({model:E});$(".response-content-type",$(this.el)).append(J.render().el)}return this};C.prototype.template=function(){if(this.model.isList){return Handlebars.templates.param_list}else{if(this.options.readOnly){if(this.model.required){return Handlebars.templates.param_readonly_required}else{return Handlebars.templates.param_readonly}}else{if(this.model.required){return Handlebars.templates.param_required}else{return Handlebars.templates.param}}}};return C})(Backbone.View);j=(function(D){y(C,D);function C(){a=C.__super__.constructor.apply(this,arguments);return a}C.prototype.events={"click a.description-link":"switchToDescription","click a.snippet-link":"switchToSnippet","mousedown .snippet":"snippetToTextArea"};C.prototype.initialize=function(){};C.prototype.render=function(){var E;E=this.template();$(this.el).html(E(this.model));this.switchToSnippet();this.isParam=this.model.isParam;if(this.isParam){$(".notice",$(this.el)).text("Click to set as parameter value")}return this};C.prototype.template=function(){return Handlebars.templates.signature};C.prototype.switchToDescription=function(E){if(E!=null){E.preventDefault()}$(".snippet",$(this.el)).hide();$(".description",$(this.el)).show();$(".description-link",$(this.el)).addClass("selected");return $(".snippet-link",$(this.el)).removeClass("selected")};C.prototype.switchToSnippet=function(E){if(E!=null){E.preventDefault()}$(".description",$(this.el)).hide();$(".snippet",$(this.el)).show();$(".snippet-link",$(this.el)).addClass("selected");return $(".description-link",$(this.el)).removeClass("selected")};C.prototype.snippetToTextArea=function(E){var F;if(this.isParam){if(E!=null){E.preventDefault()}F=$("textarea",$(this.el.parentNode.parentNode.parentNode));if($.trim(F.val())===""){return F.val(this.model.sampleJSON)}}};return C})(Backbone.View);l=(function(C){y(D,C);function D(){A=D.__super__.constructor.apply(this,arguments);return A}D.prototype.initialize=function(){};D.prototype.render=function(){var E;E=this.template();$(this.el).html(E(this.model));$("label[for=contentType]",$(this.el)).text("Response Content Type");return this};D.prototype.template=function(){return Handlebars.templates.content_type};return D})(Backbone.View);o=(function(C){y(D,C);function D(){z=D.__super__.constructor.apply(this,arguments);return z}D.prototype.initialize=function(){};D.prototype.render=function(){var E;E=this.template();$(this.el).html(E(this.model));$("label[for=responseContentType]",$(this.el)).text("Response Content Type");return this};D.prototype.template=function(){return Handlebars.templates.response_content_type};return D})(Backbone.View);n=(function(D){y(C,D);function C(){d=C.__super__.constructor.apply(this,arguments);return d}C.prototype.initialize=function(){};C.prototype.render=function(){var E;E=this.template();$(this.el).html(E(this.model));$("label[for=parameterContentType]",$(this.el)).text("Parameter content type:");return this};C.prototype.template=function(){return Handlebars.templates.parameter_content_type};return C})(Backbone.View);t=(function(D){y(C,D);function C(){b=C.__super__.constructor.apply(this,arguments);return b}C.prototype.initialize=function(){};C.prototype.render=function(){var E;E=this.template();$(this.el).html(E(this.model));return this};C.prototype.events={"click #apikey_button":"toggleApiKeyContainer","click #apply_api_key":"applyApiKey"};C.prototype.applyApiKey=function(){var E;window.authorizations.add(this.model.name,new ApiKeyAuthorization(this.model.name,$("#input_apiKey_entry").val(),this.model["in"]));window.swaggerUi.load();return E=$("#apikey_container").show()};C.prototype.toggleApiKeyContainer=function(){var E;if($("#apikey_container").length>0){E=$("#apikey_container").first();if(E.is(":visible")){return E.hide()}else{$(".auth_container").hide();return E.show()}}};C.prototype.template=function(){return Handlebars.templates.apikey_button_view};return C})(Backbone.View);k=(function(D){y(C,D);function C(){B=C.__super__.constructor.apply(this,arguments);return B}C.prototype.initialize=function(){};C.prototype.render=function(){var E;E=this.template();$(this.el).html(E(this.model));return this};C.prototype.events={"click #basic_auth_button":"togglePasswordContainer","click #apply_basic_auth":"applyPassword"};C.prototype.applyPassword=function(){var F,E,G;console.log("applying password");G=$(".input_username").val();E=$(".input_password").val();window.authorizations.add(this.model.type,new PasswordAuthorization("basic",G,E));window.swaggerUi.load();return F=$("#basic_auth_container").hide()};C.prototype.togglePasswordContainer=function(){var E;if($("#basic_auth_container").length>0){E=$("#basic_auth_container").show();if(E.is(":visible")){return E.slideUp()}else{$(".auth_container").hide();return E.show()}}};C.prototype.template=function(){return Handlebars.templates.basic_auth_button_view};return C})(Backbone.View)}).call(this); \ No newline at end of file +$(function(){$.fn.vAlign=function(){return this.each(function(c){var a=$(this).height();var d=$(this).parent().height();var b=(d-a)/2;$(this).css("margin-top",b)})};$.fn.stretchFormtasticInputWidthToParent=function(){return this.each(function(b){var d=$(this).closest("form").innerWidth();var c=parseInt($(this).closest("form").css("padding-left"),10)+parseInt($(this).closest("form").css("padding-right"),10);var a=parseInt($(this).css("padding-left"),10)+parseInt($(this).css("padding-right"),10);$(this).css("width",d-c-a)})};$("form.formtastic li.string input, form.formtastic textarea").stretchFormtasticInputWidthToParent();$("ul.downplayed li div.content p").vAlign();$("form.sandbox").submit(function(){var a=true;$(this).find("input.required").each(function(){$(this).removeClass("error");if($(this).val()==""){$(this).addClass("error");$(this).wiggle();a=false}});return a})});function clippyCopiedCallback(b){$("#api_key_copied").fadeIn().delay(1000).fadeOut()}log=function(){log.history=log.history||[];log.history.push(arguments);if(this.console){console.log(Array.prototype.slice.call(arguments)[0])}};if(Function.prototype.bind&&console&&typeof console.log=="object"){["log","info","warn","error","assert","dir","clear","profile","profileEnd"].forEach(function(a){console[a]=this.bind(console[a],console)},Function.prototype.call)}var Docs={shebang:function(){var b=$.param.fragment().split("/");b.shift();switch(b.length){case 1:var d="resource_"+b[0];Docs.expandEndpointListForResource(b[0]);$("#"+d).slideto({highlight:false});break;case 2:Docs.expandEndpointListForResource(b[0]);$("#"+d).slideto({highlight:false});var c=b.join("_");var a=c+"_content";Docs.expandOperation($("#"+a));$("#"+c).slideto({highlight:false});break}},toggleEndpointListForResource:function(b){var a=$("li#resource_"+Docs.escapeResourceName(b)+" ul.endpoints");if(a.is(":visible")){Docs.collapseEndpointListForResource(b)}else{Docs.expandEndpointListForResource(b)}},expandEndpointListForResource:function(b){var b=Docs.escapeResourceName(b);if(b==""){$(".resource ul.endpoints").slideDown();return}$("li#resource_"+b).addClass("active");var a=$("li#resource_"+b+" ul.endpoints");a.slideDown()},collapseEndpointListForResource:function(b){var b=Docs.escapeResourceName(b);$("li#resource_"+b).removeClass("active");var a=$("li#resource_"+b+" ul.endpoints");a.slideUp()},expandOperationsForResource:function(a){Docs.expandEndpointListForResource(a);if(a==""){$(".resource ul.endpoints li.operation div.content").slideDown();return}$("li#resource_"+Docs.escapeResourceName(a)+" li.operation div.content").each(function(){Docs.expandOperation($(this))})},collapseOperationsForResource:function(a){Docs.expandEndpointListForResource(a);$("li#resource_"+Docs.escapeResourceName(a)+" li.operation div.content").each(function(){Docs.collapseOperation($(this))})},escapeResourceName:function(a){return a.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g,"\\$&")},expandOperation:function(a){a.slideDown()},collapseOperation:function(a){a.slideUp()}};(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.apikey_button_view=b(function(e,k,d,j,i){this.compilerInfo=[4,">= 1.0.0"];d=this.merge(d,e.helpers);i=i||{};var g="",c,f="function",h=this.escapeExpression;g+="\n
")+"
";if(C=s.description){C=C.call(E,{hash:{},data:D})}else{C=E.description;C=typeof C===e?C.apply(E):C}if(C||C===0){B+=C}B+="
\n ";return B}function m(C,B){return'\n\n
| Parameter | \nValue | \nDescription | \nParameter Type | \nData Type | \n
|---|
| HTTP Status Code | \nReason | \nResponse Model | \n
|---|
';if(c=d.sampleJSON){c=c.call(k,{hash:{},data:i})}else{c=k.sampleJSON;c=typeof c===f?c.apply(k):c}g+=h(c)+'\n \n ").text(Q);I=$('').append(G)}else{if(P==="application/xml"||/\+xml$/.test(P)){G=$("").text(this.formatXml(N));I=$('').append(G)}else{if(P==="text/html"){G=$("").html(_.escape(N));I=$('').append(G)}else{if(/^image\//.test(P)){I=$("").text(N);I=$('').append(G)}}}}}L=I;$(".request_url",$(this.el)).html("");$(".request_url pre",$(this.el)).text(F);$(".response_code",$(this.el)).html(""+J.status+"");$(".response_body",$(this.el)).html(L);$(".response_headers",$(this.el)).html("
"+_.escape(JSON.stringify(J.headers,null," ")).replace(/\n/g,"");$(".response",$(this.el)).slideDown();$(".response_hider",$(this.el)).show();$(".response_throbber",$(this.el)).hide();K=$(".response_body",$(this.el))[0];E=this.options.swaggerOptions;if(E.highlightSizeThreshold&&J.data.length>E.highlightSizeThreshold){return K}else{return hljs.highlightBlock(K)}};C.prototype.toggleOperationContent=function(){var E;E=$("#"+Docs.escapeResourceName(this.model.parentId+"_"+this.model.nickname+"_content"));if(E.is(":visible")){return Docs.collapseOperation(E)}else{return Docs.expandOperation(E)}};return C})(Backbone.View);r=(function(D){y(C,D);function C(){e=C.__super__.constructor.apply(this,arguments);return e}C.prototype.initialize=function(){};C.prototype.render=function(){var F,E,G;G=this.template();$(this.el).html(G(this.model));if(swaggerUi.api.models.hasOwnProperty(this.model.responseModel)){F={sampleJSON:JSON.stringify(swaggerUi.api.models[this.model.responseModel].createJSONSample(),null,2),isParam:false,signature:swaggerUi.api.models[this.model.responseModel].getMockSignature()};E=new j({model:F,tagName:"div"});$(".model-signature",this.$el).append(E.render().el)}else{$(".model-signature",this.$el).html("")}return this};C.prototype.template=function(){return Handlebars.templates.status_code};return C})(Backbone.View);m=(function(D){y(C,D);function C(){c=C.__super__.constructor.apply(this,arguments);return c}C.prototype.initialize=function(){return Handlebars.registerHelper("isArray",function(F,E){if(F.type.toLowerCase()==="array"||F.allowMultiple){return E.fn(this)}else{return E.inverse(this)}})};C.prototype.render=function(){var E,F,I,G,J,H,M,N,L,K;K=this.model.type||this.model.dataType;if(typeof K==="undefined"){H=this.model.schema;if(H&&H["$ref"]){G=H["$ref"];if(G.indexOf("#/definitions/")===0){K=G.substring("#/definitions/".length)}else{K=G}}}this.model.type=K;this.model.paramType=this.model["in"]||this.model.paramType;if(this.model.paramType==="body"){this.model.isBody=true}if(K&&K.toLowerCase()==="file"){this.model.isFile=true}this.model["default"]=this.model["default"]||this.model.defaultValue;if(this.model.allowableValues){this.model.isList=true}L=this.template();$(this.el).html(L(this.model));M={sampleJSON:this.model.sampleJSON,isParam:true,signature:this.model.signature};if(this.model.sampleJSON){N=new j({model:M,tagName:"div"});$(".model-signature",$(this.el)).append(N.render().el)}else{$(".model-signature",$(this.el)).html(this.model.signature)}F=false;if(this.model.isBody){F=true}E={isParam:F};E.consumes=this.model.consumes;if(F){I=new n({model:E});$(".parameter-content-type",$(this.el)).append(I.render().el)}else{J=new o({model:E});$(".response-content-type",$(this.el)).append(J.render().el)}return this};C.prototype.template=function(){if(this.model.isList){return Handlebars.templates.param_list}else{if(this.options.readOnly){if(this.model.required){return Handlebars.templates.param_readonly_required}else{return Handlebars.templates.param_readonly}}else{if(this.model.required){return Handlebars.templates.param_required}else{return Handlebars.templates.param}}}};return C})(Backbone.View);j=(function(D){y(C,D);function C(){a=C.__super__.constructor.apply(this,arguments);return a}C.prototype.events={"click a.description-link":"switchToDescription","click a.snippet-link":"switchToSnippet","mousedown .snippet":"snippetToTextArea"};C.prototype.initialize=function(){};C.prototype.render=function(){var E;E=this.template();$(this.el).html(E(this.model));this.switchToSnippet();this.isParam=this.model.isParam;if(this.isParam){$(".notice",$(this.el)).text("Click to set as parameter value")}return this};C.prototype.template=function(){return Handlebars.templates.signature};C.prototype.switchToDescription=function(E){if(E!=null){E.preventDefault()}$(".snippet",$(this.el)).hide();$(".description",$(this.el)).show();$(".description-link",$(this.el)).addClass("selected");return $(".snippet-link",$(this.el)).removeClass("selected")};C.prototype.switchToSnippet=function(E){if(E!=null){E.preventDefault()}$(".description",$(this.el)).hide();$(".snippet",$(this.el)).show();$(".snippet-link",$(this.el)).addClass("selected");return $(".description-link",$(this.el)).removeClass("selected")};C.prototype.snippetToTextArea=function(E){var F;if(this.isParam){if(E!=null){E.preventDefault()}F=$("textarea",$(this.el.parentNode.parentNode.parentNode));if($.trim(F.val())===""){return F.val(this.model.sampleJSON)}}};return C})(Backbone.View);l=(function(C){y(D,C);function D(){A=D.__super__.constructor.apply(this,arguments);return A}D.prototype.initialize=function(){};D.prototype.render=function(){var E;E=this.template();$(this.el).html(E(this.model));$("label[for=contentType]",$(this.el)).text("Response Content Type");return this};D.prototype.template=function(){return Handlebars.templates.content_type};return D})(Backbone.View);o=(function(C){y(D,C);function D(){z=D.__super__.constructor.apply(this,arguments);return z}D.prototype.initialize=function(){};D.prototype.render=function(){var E;E=this.template();$(this.el).html(E(this.model));$("label[for=responseContentType]",$(this.el)).text("Response Content Type");return this};D.prototype.template=function(){return Handlebars.templates.response_content_type};return D})(Backbone.View);n=(function(D){y(C,D);function C(){d=C.__super__.constructor.apply(this,arguments);return d}C.prototype.initialize=function(){};C.prototype.render=function(){var E;E=this.template();$(this.el).html(E(this.model));$("label[for=parameterContentType]",$(this.el)).text("Parameter content type:");return this};C.prototype.template=function(){return Handlebars.templates.parameter_content_type};return C})(Backbone.View);t=(function(D){y(C,D);function C(){b=C.__super__.constructor.apply(this,arguments);return b}C.prototype.initialize=function(){};C.prototype.render=function(){var E;E=this.template();$(this.el).html(E(this.model));return this};C.prototype.events={"click #apikey_button":"toggleApiKeyContainer","click #apply_api_key":"applyApiKey"};C.prototype.applyApiKey=function(){var E;window.authorizations.add(this.model.name,new ApiKeyAuthorization(this.model.name,$("#input_apiKey_entry").val(),this.model["in"]));window.swaggerUi.load();return E=$("#apikey_container").show()};C.prototype.toggleApiKeyContainer=function(){var E;if($("#apikey_container").length>0){E=$("#apikey_container").first();if(E.is(":visible")){return E.hide()}else{$(".auth_container").hide();return E.show()}}};C.prototype.template=function(){return Handlebars.templates.apikey_button_view};return C})(Backbone.View);k=(function(D){y(C,D);function C(){B=C.__super__.constructor.apply(this,arguments);return B}C.prototype.initialize=function(){};C.prototype.render=function(){var E;E=this.template();$(this.el).html(E(this.model));return this};C.prototype.events={"click #basic_auth_button":"togglePasswordContainer","click #apply_basic_auth":"applyPassword"};C.prototype.applyPassword=function(){var F,E,G;console.log("applying password");G=$(".input_username").val();E=$(".input_password").val();window.authorizations.add(this.model.type,new PasswordAuthorization("basic",G,E));window.swaggerUi.load();return F=$("#basic_auth_container").hide()};C.prototype.togglePasswordContainer=function(){var E;if($("#basic_auth_container").length>0){E=$("#basic_auth_container").show();if(E.is(":visible")){return E.slideUp()}else{$(".auth_container").hide();return E.show()}}};C.prototype.template=function(){return Handlebars.templates.basic_auth_button_view};return C})(Backbone.View)}).call(this); \ No newline at end of file diff --git a/lib/swagger-client.js b/lib/swagger-client.js index cd40c01c..cb917cb7 100644 --- a/lib/swagger-client.js +++ b/lib/swagger-client.js @@ -1,8 +1,9 @@ -// swagger-client.js -// version 2.1.0-alpha.5 /** - * Array Model - **/ + * swagger-client - swagger.js is a javascript client for use with swaggering APIs. + * @version v2.1.0-alpha.5 + * @link http://swagger.io + * @license apache 2.0 + */ var ArrayModel = function(definition) { this.name = "name"; this.definition = definition || {}; @@ -57,6 +58,7 @@ ArrayModel.prototype.getMockSignature = function(modelsToIgnore) { } }; + /** * SwaggerAuthorizations applys the correct authorization to an operation being executed */ @@ -157,7 +159,8 @@ PasswordAuthorization.prototype.apply = function(obj, authorizations) { var base64encoder = this._btoa; obj.headers["Authorization"] = "Basic " + base64encoder(this.username + ":" + this.password); return true; -};var __bind = function(fn, me){ +}; +var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; @@ -238,6 +241,7 @@ Object.keys = Object.keys || (function () { return result; }; })(); + /** * PrimitiveModel **/ @@ -289,7 +293,8 @@ PrimitiveModel.prototype.getMockSignature = function(modelsToIgnore) { } } return returnVal; -};var SwaggerClient = function(url, options) { +}; +var SwaggerClient = function(url, options) { this.isBuilt = false; this.url = null; this.debug = false; @@ -316,6 +321,7 @@ PrimitiveModel.prototype.getMockSignature = function(modelsToIgnore) { if (typeof options.useJQuery === 'boolean') this.useJQuery = options.useJQuery; + this.supportedSubmitMethods = options.supportedSubmitMethods || []; this.failure = options.failure != null ? options.failure : function() {}; this.progress = options.progress != null ? options.progress : function() {}; this.spec = options.spec; @@ -763,7 +769,7 @@ Operation.prototype.supportHeaderParams = function () { }; Operation.prototype.supportedSubmitMethods = function () { - return this.resource.api.supportedSubmitMethods; + return this.parent.supportedSubmitMethods; }; Operation.prototype.getHeaderParams = function (args) { @@ -1111,11 +1117,8 @@ Operation.prototype.encodeQueryCollection = function(type, name, value) { return encoded; } -/** - * TODO this encoding needs to be changed - **/ Operation.prototype.encodeQueryParam = function(arg) { - return escape(arg); + return encodeURIComponent(arg); } /** @@ -1378,6 +1381,7 @@ e.PasswordAuthorization = PasswordAuthorization; e.CookieAuthorization = CookieAuthorization; e.SwaggerClient = SwaggerClient; e.Operation = Operation; + /** * SwaggerHttp is a wrapper for executing requests */ @@ -1389,6 +1393,10 @@ SwaggerHttp.prototype.execute = function(obj) { else this.useJQuery = this.isIE8(); + if(obj && typeof obj.body === 'object') { + obj.body = JSON.stringify(obj.body); + } + if(this.useJQuery) return new JQueryHttpClient().execute(obj); else @@ -1563,7 +1571,8 @@ ShredHttpClient.prototype.execute = function(obj) { data: response.content.data }; - var contentType = (response._headers["content-type"]||response._headers["Content-Type"]||null) + var headers = response._headers.normalized || response._headers; + var contentType = (headers["content-type"]||headers["Content-Type"]||null) if(contentType != null) { if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) { diff --git a/lib/swagger.js b/lib/swagger.js index 37854cda..214bbca3 100644 --- a/lib/swagger.js +++ b/lib/swagger.js @@ -1,8 +1,7 @@ // swagger.js -// version 2.0.47 +// version 2.0.48 (function () { - var __bind = function (fn, me) { return function () { return fn.apply(me, arguments); @@ -17,14 +16,27 @@ } }; - // if you want to apply conditional formatting of parameter values - var parameterMacro = function (value) { - return value; + /** + * allows override of the default value based on the parameter being + * supplied + **/ + var applyParameterMacro = function (model, parameter) { + var e = (typeof window !== 'undefined' ? window : exports); + if(e.parameterMacro) + return e.parameterMacro(model, parameter); + else + return parameter.defaultValue; } - // if you want to apply conditional formatting of model property values - var modelPropertyMacro = function (value) { - return value; + /** + * allows overriding the default value of an operation + **/ + var applyModelPropertyMacro = function (operation, property) { + var e = (typeof window !== 'undefined' ? window : exports); + if(e.modelPropertyMacro) + return e.modelPropertyMacro(operation, property); + else + return property.defaultValue; } if (!Array.prototype.indexOf) { @@ -58,21 +70,21 @@ Object.keys = Object.keys || (function () { var hasOwnProperty = Object.prototype.hasOwnProperty, - hasDontEnumBug = !{ toString: null }.propertyIsEnumerable("toString"), + hasDontEnumBug = !{ toString: null }.propertyIsEnumerable('toString'), DontEnums = [ - 'toString', - 'toLocaleString', - 'valueOf', - 'hasOwnProperty', - 'isPrototypeOf', - 'propertyIsEnumerable', - 'constructor' + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' ], - DontEnumsLength = DontEnums.length; + DontEnumsLength = DontEnums.length; return function (o) { - if (typeof o != "object" && typeof o != "function" || o === null) - throw new TypeError("Object.keys called on a non-object"); + if (typeof o != 'object' && typeof o != 'function' || o === null) + throw new TypeError('Object.keys called on a non-object'); var result = []; for (var name in o) { @@ -115,21 +127,32 @@ if (options.url != null) this.url = options.url; + this.swaggerRequstHeaders = options.swaggerRequstHeaders || 'application/json,application/json;charset=utf-8,*/*'; + this.defaultSuccessCallback = options.defaultSuccessCallback || null; + this.defaultErrorCallback = options.defaultErrorCallback || null; + if (options.success != null) this.success = options.success; if (typeof options.useJQuery === 'boolean') this.useJQuery = options.useJQuery; + if (options.authorizations) { + this.clientAuthorizations = options.authorizations; + } else { + var e = (typeof window !== 'undefined' ? window : exports); + this.clientAuthorizations = e.authorizations; + } + this.failure = options.failure != null ? options.failure : function () { }; this.progress = options.progress != null ? options.progress : function () { }; if (options.success != null) { this.build(); this.isBuilt = true; } - } + }; - SwaggerApi.prototype.build = function () { + SwaggerApi.prototype.build = function (mock) { if (this.isBuilt) return this; var _this = this; @@ -137,9 +160,9 @@ var obj = { useJQuery: this.useJQuery, url: this.url, - method: "get", + method: 'GET', headers: { - accept: "application/json,application/json;charset=utf-8,*/*" + accept: _this.swaggerRequstHeaders }, on: { error: function (response) { @@ -156,7 +179,7 @@ response: function (resp) { var responseObj = resp.obj || JSON.parse(resp.data); _this.swaggerVersion = responseObj.swaggerVersion; - if (_this.swaggerVersion === "1.2") { + if (_this.swaggerVersion === '1.2') { return _this.buildFromSpec(responseObj); } else { return _this.buildFrom1_1Spec(responseObj); @@ -166,6 +189,9 @@ }; var e = (typeof window !== 'undefined' ? window : exports); e.authorizations.apply(obj); + if (mock === true) + return obj; + new SwaggerHttp().execute(obj); return this; }; @@ -224,7 +250,7 @@ }; SwaggerApi.prototype.buildFrom1_1Spec = function (response) { - log("This API is using a deprecated version of Swagger! Please see http://github.com/wordnik/swagger-core/wiki for more info"); + log('This API is using a deprecated version of Swagger! Please see http://github.com/wordnik/swagger-core/wiki for more info'); if (response.apiVersion != null) this.apiVersion = response.apiVersion; this.apis = {}; @@ -272,13 +298,13 @@ }; SwaggerApi.prototype.selfReflect = function () { - var resource, resource_name, _ref; + var resource, resource_name, ref; if (this.apis == null) { return false; } - _ref = this.apis; - for (resource_name in _ref) { - resource = _ref[resource_name]; + ref = this.apis; + for (resource_name in ref) { + resource = ref[resource_name]; if (resource.ready == null) { return false; } @@ -326,11 +352,11 @@ _ref1 = resource.operations; for (operation_name in _ref1) { operation = _ref1[operation_name]; - log(" " + operation.nickname); + log(' ' + operation.nickname); _ref2 = operation.parameters; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { parameter = _ref2[_i]; - log(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description); + log(' ' + parameter.name + (parameter.required ? ' (required)' : '') + ' - ' + parameter.description); } } } @@ -340,13 +366,12 @@ var SwaggerResource = function (resourceObj, api) { var _this = this; this.api = api; - this.api = this.api; - var consumes = (this.consumes | []); - var produces = (this.produces | []); + this.swaggerRequstHeaders = api.swaggerRequstHeaders; this.path = this.api.resourcePath != null ? this.api.resourcePath : resourceObj.path; this.description = resourceObj.description; + this.authorizations = (resourceObj.authorizations || {}); - var parts = this.path.split("/"); + var parts = this.path.split('/'); this.name = parts[parts.length - 1].replace('.{format}', ''); this.basePath = this.api.basePath; this.operations = {}; @@ -360,7 +385,7 @@ this.addApiDeclaration(resourceObj); } else { if (this.path == null) { - this.api.fail("SwaggerResources must have a path."); + this.api.fail('SwaggerResources must have a path.'); } if (this.path.substring(0, 4) === 'http') { this.url = this.path.replace('{format}', 'json'); @@ -370,10 +395,10 @@ this.api.progress('fetching resource ' + this.name + ': ' + this.url); var obj = { url: this.url, - method: "get", + method: 'GET', useJQuery: this.useJQuery, headers: { - accept: "application/json,application/json;charset=utf-8,*/*" + accept: this.swaggerRequstHeaders }, on: { response: function (resp) { @@ -381,8 +406,8 @@ return _this.addApiDeclaration(responseObj); }, error: function (response) { - return _this.api.fail("Unable to read api '" + - _this.name + "' from path " + _this.url + " (server returned " + response.statusText + ")"); + return _this.api.fail('Unable to read api \'' + + _this.name + '\' from path ' + _this.url + ' (server returned ' + response.statusText + ')'); } } }; @@ -396,24 +421,24 @@ var pos, url; url = this.api.basePath; pos = url.lastIndexOf(relativeBasePath); - var parts = url.split("/"); - var rootUrl = parts[0] + "//" + parts[2]; + var parts = url.split('/'); + var rootUrl = parts[0] + '//' + parts[2]; - if (relativeBasePath.indexOf("http") === 0) + if (relativeBasePath.indexOf('http') === 0) return relativeBasePath; - if (relativeBasePath === "/") + if (relativeBasePath === '/') return rootUrl; - if (relativeBasePath.substring(0, 1) == "/") { + if (relativeBasePath.substring(0, 1) == '/') { // use root + relative return rootUrl + relativeBasePath; } else { - var pos = this.basePath.lastIndexOf("/"); + var pos = this.basePath.lastIndexOf('/'); var base = this.basePath.substring(0, pos); - if (base.substring(base.length - 1) == "/") + if (base.substring(base.length - 1) == '/') return base + relativeBasePath; else - return base + "/" + relativeBasePath; + return base + '/' + relativeBasePath; } }; @@ -423,7 +448,7 @@ if (response.consumes != null) this.consumes = response.consumes; if ((response.basePath != null) && response.basePath.replace(/\s/g, '').length > 0) - this.basePath = response.basePath.indexOf("http") === -1 ? this.getAbsoluteBasePath(response.basePath) : response.basePath; + this.basePath = response.basePath.indexOf('http') === -1 ? this.getAbsoluteBasePath(response.basePath) : response.basePath; this.addModels(response.models); if (response.apis) { @@ -475,11 +500,11 @@ produces = this.produces; var type = (o.type || o.responseClass); - if (type === "array") { + if (type === 'array') { ref = null; if (o.items) - ref = o.items["type"] || o.items["$ref"]; - type = "array[" + ref + "]"; + ref = o.items['type'] || o.items['$ref']; + type = 'array[' + ref + ']'; } var responseMessages = o.responseMessages; var method = o.method; @@ -515,22 +540,6 @@ return op; }; - SwaggerResource.prototype.help = function () { - var op = this.operations; - var output = []; - var operation_name; - for (operation_name in op) { - operation = op[operation_name]; - var msg = " " + operation.nickname; - for (var i = 0; i < operation.parameters; i++) { - parameter = operation.parameters[i]; - msg.concat(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description); - } - output.push(msg); - } - return output; - }; - var SwaggerModel = function (modelName, obj) { this.name = obj.id != null ? obj.id : modelName; this.properties = []; @@ -544,7 +553,7 @@ } } } - var prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName]); + var prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName], this); this.properties.push(prop); } } @@ -572,7 +581,6 @@ } var strong = ''; - var stronger = ''; var strongClose = ''; var classOpen = strong + this.name + ' {' + strongClose; var classClose = strong + '}' + strongClose; @@ -607,13 +615,13 @@ } }; - var SwaggerModelProperty = function (name, obj) { + var SwaggerModelProperty = function (name, obj, model) { this.name = name; - this.dataType = obj.type || obj.dataType || obj["$ref"]; + this.dataType = obj.type || obj.dataType || obj['$ref']; this.isCollection = this.dataType && (this.dataType.toLowerCase() === 'array' || this.dataType.toLowerCase() === 'list' || this.dataType.toLowerCase() === 'set'); this.descr = obj.description; this.required = obj.required; - this.defaultValue = modelPropertyMacro(obj.defaultValue); + this.defaultValue = applyModelPropertyMacro(obj, model); if (obj.items != null) { if (obj.items.type != null) { this.refDataType = obj.items.type; @@ -627,14 +635,14 @@ this.valueType = obj.allowableValues.valueType; this.values = obj.allowableValues.values; if (this.values != null) { - this.valuesString = "'" + this.values.join("' or '") + "'"; + this.valuesString = '\'' + this.values.join('\' or \'') + '\''; } } - if (obj["enum"] != null) { - this.valueType = "string"; - this.values = obj["enum"]; + if (obj['enum'] != null) { + this.valueType = 'string'; + this.values = obj['enum']; if (this.values != null) { - this.valueString = "'" + this.values.join("' or '") + "'"; + this.valueString = '\'' + this.values.join('\' or \'') + '\''; } } } @@ -661,14 +669,14 @@ var result; if ((typeof this.defaultValue !== 'undefined') && this.defaultValue !== null) { result = this.defaultValue; - } else if (value === "integer") { + } else if (value === 'integer') { result = 0; - } else if (value === "boolean") { + } else if (value === 'boolean') { result = false; - } else if (value === "double" || value === "number") { + } else if (value === 'double' || value === 'number') { result = 0.0; - } else if (value === "string") { - result = ""; + } else if (value === 'string') { + result = ''; } else { result = value; } @@ -683,7 +691,7 @@ } str += ')'; if (this.values != null) { - str += " = ['" + this.values.join("' or '") + "']"; + str += ' = ["' + this.values.join('\' or \'') + '\']'; } if (this.descr != null) { str += ': ' + this.descr + ''; @@ -695,20 +703,20 @@ var _this = this; var errors = []; - this.nickname = (nickname || errors.push("SwaggerOperations must have a nickname.")); - this.path = (path || errors.push("SwaggerOperation " + nickname + " is missing path.")); - this.method = (method || errors.push("SwaggerOperation " + nickname + " is missing method.")); + this.nickname = (nickname || errors.push('SwaggerOperations must have a nickname.')); + this.path = (path || errors.push('SwaggerOperation ' + nickname + ' is missing path.')); + this.method = (method || errors.push('SwaggerOperation ' + nickname + ' is missing method.')); this.parameters = parameters != null ? parameters : []; this.summary = summary; this.notes = notes; this.type = type; this.responseMessages = (responseMessages || []); - this.resource = (resource || errors.push("Resource is required")); + this.resource = (resource || errors.push('Resource is required')); this.consumes = consumes; this.produces = produces; - this.authorizations = authorizations; + this.authorizations = typeof authorizations !== 'undefined' ? authorizations : resource.authorizations; this.deprecated = deprecated; - this["do"] = __bind(this["do"], this); + this['do'] = __bind(this['do'], this); if (errors.length > 0) { console.error('SwaggerOperation errors', errors, arguments); @@ -717,7 +725,7 @@ this.path = this.path.replace('{format}', 'json'); this.method = this.method.toLowerCase(); - this.isGetMethod = this.method === "get"; + this.isGetMethod = this.method === 'GET'; this.resourceName = this.resource.name; if (typeof this.type !== 'undefined' && this.type === 'void') @@ -741,12 +749,12 @@ if (type && type.toLowerCase() === 'boolean') { param.allowableValues = {}; - param.allowableValues.values = ["true", "false"]; + param.allowableValues.values = ['true', 'false']; } param.signature = this.getSignature(type, this.resource.models); param.sampleJSON = this.getSampleJSON(type, this.resource.models); - var enumValue = param["enum"]; + var enumValue = param['enum']; if (enumValue != null) { param.isList = true; param.allowableValues = {}; @@ -769,7 +777,7 @@ } } else if (param.allowableValues != null) { - if (param.allowableValues.valueType === "RANGE") + if (param.allowableValues.valueType === 'RANGE') param.isRange = true; else param.isList = true; @@ -794,14 +802,29 @@ } } } - param.defaultValue = parameterMacro(param.defaultValue); + param.defaultValue = applyParameterMacro(param, this); } - this.resource[this.nickname] = function (args, callback, error) { - return _this["do"](args, callback, error); + var defaultSuccessCallback = this.resource.api.defaultSuccessCallback || null; + var defaultErrorCallback = this.resource.api.defaultErrorCallback || null; + + this.resource[this.nickname] = function (args, opts, callback, error) { + var arg1 = args, + arg2 = opts, + arg3 = callback || defaultSuccessCallback, + arg4 = error || defaultErrorCallback; + if(typeof opts === 'function') { + arg2 = {}; + arg3 = opts; + arg4 = error; + } + return _this['do'](arg1, arg2, arg3, arg4); }; this.resource[this.nickname].help = function () { return _this.help(); }; + this.resource[this.nickname].asCurl = function (args) { + return _this.asCurl(args); + }; } SwaggerOperation.prototype.isListType = function (type) { @@ -834,9 +857,9 @@ val = isPrimitive ? void 0 : (listType != null ? models[listType].createJSONSample() : models[type].createJSONSample()); if (val) { val = listType ? [val] : val; - if (typeof val == "string") + if (typeof val == 'string') return val; - else if (typeof val === "object") { + else if (typeof val === 'object') { var t = val; if (val instanceof Array && val.length > 0) { t = val[0]; @@ -853,22 +876,17 @@ } }; - SwaggerOperation.prototype["do"] = function (args, opts, callback, error) { - var key, param, params, possibleParams, req, requestContentType, responseContentType, value, _i, _len, _ref; - if (args == null) { - args = {}; - } - if (opts == null) { - opts = {}; - } - requestContentType = null; - responseContentType = null; - if ((typeof args) === "function") { + SwaggerOperation.prototype['do'] = function (args, opts, callback, error) { + var key, param, params, possibleParams, req, value; + args = args || {}; + opts = opts || {}; + + if ((typeof args) === 'function') { error = opts; callback = args; args = {}; } - if ((typeof opts) === "function") { + if ((typeof opts) === 'function') { error = callback; callback = opts; } @@ -884,9 +902,9 @@ if (response != null) { content = response.data; } else { - content = "no data"; + content = 'no data'; } - return log("default callback: " + content); + return log('default callback: ' + content); }; } params = {}; @@ -895,19 +913,26 @@ params.headers = args.headers; delete args.headers; } + // allow override from the opts + if(opts && opts.responseContentType) { + params.headers['Content-Type'] = opts.responseContentType; + } + if(opts && opts.requestContentType) { + params.headers['Accept'] = opts.requestContentType; + } var possibleParams = []; for (var i = 0; i < this.parameters.length; i++) { var param = this.parameters[i]; if (param.paramType === 'header') { - if (args[param.name]) + if (typeof args[param.name] !== 'undefined') params.headers[param.name] = args[param.name]; } else if (param.paramType === 'form' || param.paramType.toLowerCase() === 'file') possibleParams.push(param); - else if (param.paramType === 'body' && param.name !== 'body') { + else if (param.paramType === 'body' && param.name !== 'body' && typeof args[param.name] !== 'undefined') { if (args.body) { - throw new Error("Saw two body params in an API listing; expecting a max of one."); + throw new Error('Saw two body params in an API listing; expecting a max of one.'); } args.body = args[param.name]; } @@ -927,7 +952,6 @@ } } } - req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this); if (opts.mock != null) { return req; @@ -937,26 +961,26 @@ }; SwaggerOperation.prototype.pathJson = function () { - return this.path.replace("{format}", "json"); + return this.path.replace('{format}', 'json'); }; SwaggerOperation.prototype.pathXml = function () { - return this.path.replace("{format}", "xml"); + return this.path.replace('{format}', 'xml'); }; SwaggerOperation.prototype.encodePathParam = function (pathParam) { var encParts, part, parts, _i, _len; pathParam = pathParam.toString(); - if (pathParam.indexOf("/") === -1) { + if (pathParam.indexOf('/') === -1) { return encodeURIComponent(pathParam); } else { - parts = pathParam.split("/"); + parts = pathParam.split('/'); encParts = []; for (_i = 0, _len = parts.length; _i < _len; _i++) { part = parts[_i]; encParts.push(encodeURIComponent(part)); } - return encParts.join("/"); + return encParts.join('/'); } }; @@ -966,18 +990,18 @@ for (var i = 0; i < params.length; i++) { var param = params[i]; if (param.paramType === 'path') { - if (args[param.name]) { + if (typeof args[param.name] !== 'undefined') { // apply path params and remove from args var reg = new RegExp('\\{\\s*?' + param.name + '.*?\\}(?=\\s*?(\\/?|$))', 'gi'); url = url.replace(reg, this.encodePathParam(args[param.name])); delete args[param.name]; } else - throw "" + param.name + " is a required path param."; + throw '' + param.name + ' is a required path param.'; } } - var queryParams = ""; + var queryParams = ''; for (var i = 0; i < params.length; i++) { var param = params[i]; if(param.paramType === 'query') { @@ -994,11 +1018,11 @@ queryParams += encodeURIComponent(param.name) + '=' + output; } else { - if (args[param.name]) { + if (typeof args[param.name] !== 'undefined') { queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]); } else { if (param.required) - throw "" + param.name + " is a required query param."; + throw '' + param.name + ' is a required query param.'; } } } @@ -1042,17 +1066,35 @@ }; SwaggerOperation.prototype.help = function () { - var msg = ""; + var msg = ''; var params = this.parameters; for (var i = 0; i < params.length; i++) { var param = params[i]; - if (msg !== "") - msg += "\n"; - msg += "* " + param.name + (param.required ? ' (required)' : '') + " - " + param.description; + if (msg !== '') + msg += '\n'; + msg += '* ' + param.name + (param.required ? ' (required)' : '') + " - " + param.description; } return msg; }; + SwaggerOperation.prototype.asCurl = function (args) { + var results = []; + var i; + + var headers = SwaggerRequest.prototype.setHeaders(args, {}, this); + for(i = 0; i < this.parameters.length; i++) { + var param = this.parameters[i]; + if(param.paramType && param.paramType === 'header' && args[param.name]) { + headers[param.name] = args[param.name]; + } + } + + var key; + for (key in headers) { + results.push('--header "' + key + ': ' + headers[key] + '"'); + } + return 'curl ' + (results.join(' ')) + ' ' + this.urlify(args); + }; SwaggerOperation.prototype.formatXml = function (xml) { var contexp, formatted, indent, lastType, lines, ln, pad, reg, transitions, wsexp, _fn, _i, _len; @@ -1131,13 +1173,13 @@ var _this = this; var errors = []; this.useJQuery = (typeof operation.resource.useJQuery !== 'undefined' ? operation.resource.useJQuery : null); - this.type = (type || errors.push("SwaggerRequest type is required (get/post/put/delete/patch/options).")); - this.url = (url || errors.push("SwaggerRequest url is required.")); + this.type = (type || errors.push('SwaggerRequest type is required (get/post/put/delete/patch/options).')); + this.url = (url || errors.push('SwaggerRequest url is required.')); this.params = params; this.opts = opts; - this.successCallback = (successCallback || errors.push("SwaggerRequest successCallback is required.")); - this.errorCallback = (errorCallback || errors.push("SwaggerRequest error callback is required.")); - this.operation = (operation || errors.push("SwaggerRequest operation is required.")); + this.successCallback = (successCallback || errors.push('SwaggerRequest successCallback is required.')); + this.errorCallback = (errorCallback || errors.push('SwaggerRequest error callback is required.')); + this.operation = (operation || errors.push('SwaggerRequest operation is required.')); this.execution = execution; this.headers = (params.headers || {}); @@ -1148,37 +1190,37 @@ this.type = this.type.toUpperCase(); // set request, response content type headers - var headers = this.setHeaders(params, this.operation); + var headers = this.setHeaders(params, opts, this.operation); var body = params.body; // encode the body for form submits - if (headers["Content-Type"]) { + if (headers['Content-Type']) { var values = {}; var i; var operationParams = this.operation.parameters; for (i = 0; i < operationParams.length; i++) { var param = operationParams[i]; - if (param.paramType === "form") + if (param.paramType === 'form') values[param.name] = param; } - if (headers["Content-Type"].indexOf("application/x-www-form-urlencoded") === 0) { - var encoded = ""; + if (headers['Content-Type'].indexOf('application/x-www-form-urlencoded') === 0) { + var encoded = ''; var key, value; for (key in values) { value = this.params[key]; if (typeof value !== 'undefined') { - if (encoded !== "") - encoded += "&"; + if (encoded !== '') + encoded += '&'; encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value); } } body = encoded; } - else if (headers["Content-Type"].indexOf("multipart/form-data") === 0) { + else if (headers['Content-Type'].indexOf('multipart/form-data') === 0) { // encode the body for form submits - var data = ""; - var boundary = "----SwaggerFormBoundary" + Date.now(); + var data = ''; + var boundary = '----SwaggerFormBoundary' + Date.now(); var key, value; for (key in values) { value = this.params[key]; @@ -1186,11 +1228,11 @@ data += '--' + boundary + '\n'; data += 'Content-Disposition: form-data; name="' + key + '"'; data += '\n\n'; - data += value + "\n"; + data += value + '\n'; } } - data += "--" + boundary + "--\n"; - headers["Content-Type"] = "multipart/form-data; boundary=" + boundary; + data += '--' + boundary + '--\n'; + headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary; body = data; } } @@ -1218,13 +1260,22 @@ } } }; - var e; - if (typeof window !== 'undefined') { - e = window; + + var status = false; + if (this.operation.resource && this.operation.resource.api && this.operation.resource.api.clientAuthorizations) { + // Get the client authorizations from the resource declaration + status = this.operation.resource.api.clientAuthorizations.apply(obj, this.operation.authorizations); } else { - e = exports; + // Get the client authorization from the default authorization declaration + var e; + if (typeof window !== 'undefined') { + e = window; + } else { + e = exports; + } + status = e.authorizations.apply(obj, this.operation.authorizations); } - var status = e.authorizations.apply(obj, this.operation.authorizations); + if (opts.mock == null) { if (status !== false) { new SwaggerHttp().execute(obj); @@ -1238,12 +1289,12 @@ return obj; }; - SwaggerRequest.prototype.setHeaders = function (params, operation) { + SwaggerRequest.prototype.setHeaders = function (params, opts, operation) { // default type - var accepts = "application/json"; - var consumes = "application/json"; + var accepts = opts.responseContentType || 'application/json'; + var consumes = opts.requestContentType || 'application/json'; - var allDefinedParams = this.operation.parameters; + var allDefinedParams = operation.parameters; var definedFormParams = []; var definedFileParams = []; var body = params.body; @@ -1253,11 +1304,11 @@ var i; for (i = 0; i < allDefinedParams.length; i++) { var param = allDefinedParams[i]; - if (param.paramType === "form") + if (param.paramType === 'form') definedFormParams.push(param); - else if (param.paramType === "file") + else if (param.paramType === 'file') definedFileParams.push(param); - else if (param.paramType === "header" && this.params.headers) { + else if (param.paramType === 'header' && this.params.headers) { var key = param.name; var headerValue = this.params.headers[param.name]; if (typeof this.params.headers[param.name] !== 'undefined') @@ -1266,60 +1317,47 @@ } // if there's a body, need to set the accepts header via requestContentType - if (body && (this.type === "POST" || this.type === "PUT" || this.type === "PATCH" || this.type === "DELETE")) { + if (body && (this.type === 'POST' || this.type === 'PUT' || this.type === 'PATCH' || this.type === 'DELETE')) { if (this.opts.requestContentType) consumes = this.opts.requestContentType; } else { // if any form params, content type must be set if (definedFormParams.length > 0) { if (definedFileParams.length > 0) - consumes = "multipart/form-data"; + consumes = 'multipart/form-data'; else - consumes = "application/x-www-form-urlencoded"; + consumes = 'application/x-www-form-urlencoded'; } - else if (this.type === "DELETE") - body = "{}"; - else if (this.type != "DELETE") + else if (this.type === 'DELETE') + body = '{}'; + else if (this.type != 'DELETE') consumes = null; } if (consumes && this.operation.consumes) { if (this.operation.consumes.indexOf(consumes) === -1) { - log("server doesn't consume " + consumes + ", try " + JSON.stringify(this.operation.consumes)); - consumes = this.operation.consumes[0]; + log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.operation.consumes)); } } - if (this.opts.responseContentType) { + if (this.opts && this.opts.responseContentType) { accepts = this.opts.responseContentType; } else { - accepts = "application/json"; + accepts = 'application/json'; } - if (accepts && this.operation.produces) { - if (this.operation.produces.indexOf(accepts) === -1) { - log("server can't produce " + accepts); - accepts = this.operation.produces[0]; + if (accepts && operation.produces) { + if (operation.produces.indexOf(accepts) === -1) { + log('server can\'t produce ' + accepts); } } - if ((consumes && body !== "") || (consumes === "application/x-www-form-urlencoded")) - headers["Content-Type"] = consumes; + if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded')) + headers['Content-Type'] = consumes; if (accepts) - headers["Accept"] = accepts; + headers['Accept'] = accepts; return headers; } - SwaggerRequest.prototype.asCurl = function () { - var results = []; - if (this.headers) { - var key; - for (key in this.headers) { - results.push("--header \"" + key + ": " + this.headers[v] + "\""); - } - } - return "curl " + (results.join(" ")) + " " + this.url; - }; - /** * SwaggerHttp is a wrapper for executing requests */ @@ -1357,7 +1395,7 @@ * Since we are using closures here we need to alias it for internal use. */ var JQueryHttpClient = function (options) { - "use strict"; + this.options = options || {}; if (!jQuery) { var jQuery = window.jQuery; } @@ -1376,9 +1414,9 @@ results = []; var key; for (key in obj.headers) { - if (key.toLowerCase() === "content-type") { + if (key.toLowerCase() === 'content-type') { results.push(obj.contentType = obj.headers[key]); - } else if (key.toLowerCase() === "accept") { + } else if (key.toLowerCase() === 'accept') { results.push(obj.accepts = obj.headers[key]); } else { results.push(xhr.setRequestHeader(key, obj.headers[key])); @@ -1389,22 +1427,22 @@ }; obj.data = obj.body; - obj.complete = function (response, textStatus, opts) { + obj.complete = function (response) { var headers = {}, - headerArray = response.getAllResponseHeaders().split("\n"); + headerArray = response.getAllResponseHeaders().split('\n'); for (var i = 0; i < headerArray.length; i++) { var toSplit = headerArray[i].trim(); if (toSplit.length === 0) continue; - var separator = toSplit.indexOf(":"); + var separator = toSplit.indexOf(':'); if (separator === -1) { // Name but no value in the header headers[toSplit] = null; continue; } var name = toSplit.substring(0, separator).trim(), - value = toSplit.substring(separator + 1).trim(); + value = toSplit.substring(separator + 1).trim(); headers[name] = value; } @@ -1416,11 +1454,11 @@ headers: headers }; - var contentType = (headers["content-type"] || headers["Content-Type"] || null) + var contentType = (headers['content-type'] || headers['Content-Type'] || null) if (contentType != null) { - if (contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) { - if (response.responseText && response.responseText !== "") + if (contentType.indexOf('application/json') == 0 || contentType.indexOf('+json') > 0) { + if (response.responseText && response.responseText !== '') out.obj = JSON.parse(response.responseText); else out.obj = {} @@ -1446,14 +1484,12 @@ this.options = (options || {}); this.isInitialized = false; - var identity, toString; - if (typeof window !== 'undefined') { - this.Shred = require("./shred"); - this.content = require("./shred/content"); + this.Shred = require('./shred'); + this.content = require('./shred/content'); } else - this.Shred = require("shred"); + this.Shred = require('shred'); this.shred = new this.Shred(); } @@ -1462,7 +1498,7 @@ this.registerProcessors(this.shred); } - ShredHttpClient.prototype.registerProcessors = function (shred) { + ShredHttpClient.prototype.registerProcessors = function () { var identity = function (x) { return x; }; @@ -1471,12 +1507,12 @@ }; if (typeof window !== 'undefined') { - this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], { + this.content.registerProcessor(['application/json; charset=utf-8', 'application/json', 'json'], { parser: identity, stringify: toString }); } else { - this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], { + this.Shred.registerProcessor(['application/json; charset=utf-8', 'application/json', 'json'], { parser: identity, stringify: toString }); @@ -1499,16 +1535,16 @@ }; var headers = response._headers.normalized || response._headers; - var contentType = (headers["content-type"] || headers["Content-Type"] || null) + var contentType = (headers['content-type'] || headers['Content-Type'] || null) if (contentType != null) { - if (contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) { - if (response.content.data && response.content.data !== "") + if (contentType.indexOf('application/json') == 0 || contentType.indexOf('+json') > 0) { + if (response.content.data && response.content.data !== '') try { out.obj = JSON.parse(response.content.data); } catch (ex) { // do not set out.obj - log ("unable to parse JSON content"); + log('unable to parse JSON content'); } else out.obj = {} @@ -1547,14 +1583,6 @@ if (obj) return cb.error(transformError(err)); }, - redirect: function (response) { - if (obj) - return cb.redirect(transform(response)); - }, - 307: function (response) { - if (obj) - return cb.redirect(transform(response)); - }, response: function (response) { if (obj) return cb.response(transform(response)); @@ -1569,8 +1597,11 @@ /** * SwaggerAuthorizations applys the correct authorization to an operation being executed */ - var SwaggerAuthorizations = function () { + var SwaggerAuthorizations = function (name, auth) { this.authz = {}; + if(name && auth) { + this.authz[name] = auth; + } }; SwaggerAuthorizations.prototype.add = function (name, auth) { @@ -1621,14 +1652,14 @@ this.delimiter = delimiter; }; - ApiKeyAuthorization.prototype.apply = function (obj, authorizations) { - if (this.type === "query") { + ApiKeyAuthorization.prototype.apply = function (obj) { + if (this.type === 'query') { if (obj.url.indexOf('?') > 0) - obj.url = obj.url + "&" + this.name + "=" + this.value; + obj.url = obj.url + '&' + this.name + '=' + this.value; else - obj.url = obj.url + "?" + this.name + "=" + this.value; + obj.url = obj.url + '?' + this.name + '=' + this.value; return true; - } else if (this.type === "header") { + } else if (this.type === 'header') { if (typeof obj.headers[this.name] !== 'undefined') { if (typeof this.delimiter !== 'undefined') obj.headers[this.name] = obj.headers[this.name] + this.delimiter + this.value; @@ -1643,7 +1674,7 @@ this.cookie = cookie; } - CookieAuthorization.prototype.apply = function (obj, authorizations) { + CookieAuthorization.prototype.apply = function (obj) { obj.cookieJar = obj.cookieJar || CookieJar(); obj.cookieJar.setCookie(this.cookie); return true; @@ -1660,25 +1691,23 @@ if (typeof window !== 'undefined') this._btoa = btoa; else - this._btoa = require("btoa"); + this._btoa = require('btoa'); }; - PasswordAuthorization.prototype.apply = function (obj, authorizations) { + PasswordAuthorization.prototype.apply = function (obj) { var base64encoder = this._btoa; - obj.headers["Authorization"] = "Basic " + base64encoder(this.username + ":" + this.password); + obj.headers['Authorization'] = 'Basic ' + base64encoder(this.username + ':' + this.password); return true; }; var e = (typeof window !== 'undefined' ? window : exports); var sampleModels = {}; - var cookies = {}; - e.parameterMacro = parameterMacro; - e.modelPropertyMacro = modelPropertyMacro; e.SampleModels = sampleModels; e.SwaggerHttp = SwaggerHttp; e.SwaggerRequest = SwaggerRequest; + e.SwaggerAuthorizations = SwaggerAuthorizations; e.authorizations = new SwaggerAuthorizations(); e.ApiKeyAuthorization = ApiKeyAuthorization; e.PasswordAuthorization = PasswordAuthorization; @@ -1690,6 +1719,7 @@ e.SwaggerModelProperty = SwaggerModelProperty; e.SwaggerResource = SwaggerResource; e.SwaggerApi = SwaggerApi; + e.log = log; })();
")+"