From 4aad129db3b2f90f4e168df17bbd85a21e1cc151 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Mon, 10 Feb 2014 12:51:18 -0800 Subject: [PATCH 01/13] got rid of swagger.coffee for a pure js & cleaner version --- lib/swagger.js | 958 ++++++++++++++++++--------------------- src/swagger.coffee | 1075 -------------------------------------------- 2 files changed, 449 insertions(+), 1584 deletions(-) delete mode 100644 src/swagger.coffee diff --git a/lib/swagger.js b/lib/swagger.js index a7b1abccb..de9aa4f48 100644 --- a/lib/swagger.js +++ b/lib/swagger.js @@ -1,6 +1,451 @@ -// Generated by CoffeeScript 1.6.3 +var SwaggerRequest = function(type, url, params, opts, successCallback, errorCallback, operation, execution) { + var _this = this; + var errors = []; + + 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.execution = execution; + this.headers = (params.headers||{}); + + if(errors.length > 0) { + throw errors; + } + + // if (this.type == null) + // throw "SwaggerRequest type is required (get/post/put/delete/patch/options)."; + // if (this.url == null) + // throw "SwaggerRequest url is required."; + // if (this.successCallback == null) + // throw "SwaggerRequest successCallback is required."; + // if (this.errorCallback == null) + // throw "SwaggerRequest error callback is required."; + // if (this.operation == null) + // throw "SwaggerRequest operation is required."; + + + this.type = this.type.toUpperCase(); + + var myHeaders = {}; + var body = params.body; + var parent = params["parent"]; + var requestContentType = "application/json"; + + var formParams = []; + var fileParams = []; + var params = this.operation.parameters; + + + for(i = 0; i < params.length; i++) { + var param = params[i]; + if(param.paramType === "form") + formParams.push(param); + else if(param.paramType === "file") + fileParams.push(param); + } + + + if (body && (this.type === "POST" || this.type === "PUT" || this.type === "PATCH")) { + if (this.opts.requestContentType) { + requestContentType = this.opts.requestContentType; + } + } else { + // if any form params, content type must be set + if(formParams.length > 0) { + if(fileParams.length > 0) + requestContentType = "application/x-www-form-urlencoded" + else + requestContentType = "multipart/form-data" + } + else if (this.type != "DELETE") + requestContentType = null; + } + + if (requestContentType && this.operation.consumes) { + if (this.operation.consumes[requestContentType] === 'undefined') { + log("server doesn't consume " + requestContentType + ", try " + JSON.stringify(this.operation.consumes)); + if (this.requestContentType === null) { + requestContentType = this.operation.consumes[0]; + } + } + } + + responseContentType = null; + if (this.type === "POST" || this.type === "GET" || this.type === "PATCH") { + if (this.opts.responseContentType) { + responseContentType = this.opts.responseContentType; + } else { + responseContentType = "application/json"; + } + } else { + responseContentType = null; + } + if (responseContentType && this.operation.produces) { + if (this.operation.produces[responseContentType] === 'undefined') { + log("server can't produce " + responseContentType); + } + } + if (requestContentType && requestContentType.indexOf("application/x-www-form-urlencoded") === 0) { + var fields = {}; + var possibleParams = {}; + var values = {}; + + for(i = 0; i < formParams.length; i++){ + var param = formParams[i]; + values[param.name] = param; + } + + var encoded = ""; + for(key in values) { + value = values[key]; + if(encoded !== "") + encoded += "&"; + encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value); + } + body = encoded + } + for (name in this.headers) + myHeaders[name] = this.headers[name]; + if (requestContentType) + myHeaders["Content-Type"] = requestContentType; + if (responseContentType) + myHeaders["Accept"] = responseContentType; + + if (!((this.headers != null) && (this.headers.mock != null))) { + obj = { + url: this.url, + method: this.type, + headers: myHeaders, + body: body, + useJQuery: this.useJQuery, + on: { + error: function(response) { + return _this.errorCallback(response, _this.opts.parent); + }, + redirect: function(response) { + return _this.successCallback(response, _this.opts.parent); + }, + 307: function(response) { + return _this.successCallback(response, _this.opts.parent); + }, + response: function(response) { + return _this.successCallback(response, _this.opts.parent); + } + } + }; + var e; + if (typeof window !== 'undefined') { + e = window; + } else { + e = exports; + } + status = e.authorizations.apply(obj, this.operation.authorizations); + if (opts.mock == null) { + if (status !== false) { + new SwaggerHttp().execute(obj); + } else { + obj.canceled = true; + } + } else { + return obj; + } + } +}; + +SwaggerRequest.prototype.asCurl = function() { + var header_args, k, v; + header_args = (function() { + var _ref, _results; + _ref = this.headers; + _results = []; + for (k in _ref) { + v = _ref[k]; + _results.push("--header \"" + k + ": " + v + "\""); + } + return _results; + }).call(this); + return "curl " + (header_args.join(" ")) + " " + this.url; +}; + +/* + * SwaggerHttp is a wrapper for executing requests + */ +var SwaggerHttp = function(options) { + options = (options||{}); + this.useJQuery = options["useJQuery"]||false; +}; + +SwaggerHttp.prototype.execute = function(obj) { + if(this.useJQuery) + return new JQueryHttpClient().execute(obj); + else + return new ShredHttpClient().execute(obj); +} + +SwaggerHttp.prototype.isIE8 = function() { + var detectedIE = false; + if (typeof navigator !== 'undefined' && navigator.userAgent) { + nav = navigator.userAgent.toLowerCase(); + if (nav.indexOf('msie') !== -1) { + var version = parseInt(nav.split('msie')[1]); + if (version <= 8) { + detectedIE = true; + } + } + } + return detectedIE; +}; + +/* + * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic + */ +var JQueryHttpClient = function(options) {} + +JQueryHttpClient.prototype.execute = function(obj) { + var cb = obj.on; + var request = obj; + + obj.type = obj.method; + obj.cache = false; + + obj.beforeSend = function(xhr) { + var key, results; + if (obj.headers) { + results = []; + for (key in obj.headers) { + if (key.toLowerCase() === "content-type") { + results.push(obj.contentType = obj.headers[key]); + } else if (key.toLowerCase() === "accept") { + results.push(obj.accepts = obj.headers[key]); + } else { + results.push(xhr.setRequestHeader(key, obj.headers[key])); + } + } + return results; + } + }; + + obj.data = obj.body; + obj.complete = function(response, textStatus, opts) { + headers = {}; + headerArray = response.getAllResponseHeaders().split(":"); + + for(i = 0; i < headerArray.length / 2; i++) + headers[headerArray[i] = headerArray[i+1]]; + + out = { + headers: headers, + url: request.url, + method: request.method, + status: response.status, + data: response.responseText, + headers: headers + }; + + if(response.status >= 200 && response.status < 300) + cb.response(out); + else if(response.status === 0 || (response.status >= 400 && response.status < 599)) + cb.error(out); + else + return cb.response(out); + }; + + $.support.cors = true; + return $.ajax(obj); +} + +/* + * ShredHttpClient is a light-weight, node or browser HTTP client + */ +var ShredHttpClient = function(options) { + this.options = (options||{}); + this.isInitialized = false; + + var identity, toString; + + if (typeof window !== 'undefined') { + this.Shred = require("./shred"); + this.content = require("./shred/content"); + } + else + this.Shred = require("shred"); + this.shred = new this.Shred(); +} + +ShredHttpClient.prototype.initShred = function () { + this.isInitialized = true; + this.registerProcessors(this.shred); +} + +ShredHttpClient.prototype.registerProcessors = function(shred) { + var identity = function(x) { + return x; + }; + var toString = function(x) { + return x.toString(); + }; + + if (typeof window !== 'undefined') { + 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"], { + parser: identity, + stringify: toString + }); + } +} + +ShredHttpClient.prototype.execute = function(obj) { + if(!this.isInitialized) + this.initShred(); + + var cb = obj.on, res; + + var transform = function(response) { + return { + headers: response._headers, + url: response.request.url, + method: response.request.method, + status: response.status, + data: response.content.data + }; + }; + + res = { + error: function(response) { + if (obj) { + return cb.error(transform(response)); + } + }, + 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)); + } + } + }; + if (obj) { + obj.on = res; + } + return this.shred.request(obj); +}; + +/** + * SwaggerAuthorizations applys the correct authorization to an operation being executed + */ +var SwaggerAuthorizations = function() { + this.authz = {}; +}; + +SwaggerAuthorizations.prototype.add = function(name, auth) { + this.authz[name] = auth; + return auth; +}; + +SwaggerAuthorizations.prototype.remove = function(name) { + return delete this.authz[name]; +}; + +SwaggerAuthorizations.prototype.apply = function(obj, authorizations) { + status = null; + for (key in this.authz) { + value = this.authz[key]; + result = value.apply(obj, authorizations); + if (result === false) + status = false; + if (result === true) + status = true; + } + return status; +}; + +/** + * ApiKeyAuthorization allows a query param or header to be injected + */ +var ApiKeyAuthorization = function(name, value, type) { + this.name = name; + this.value = value; + this.type = type; +}; + +ApiKeyAuthorization.prototype.apply = function(obj, authorizations) { + if (this.type === "query") { + if (obj.url.indexOf('?') > 0) + obj.url = obj.url + "&" + this.name + "=" + this.value; + else + obj.url = obj.url + "?" + this.name + "=" + this.value; + return true; + } else if (this.type === "header") { + obj.headers[this.name] = this.value; + return true; + } +}; + +/** + * Password Authorization is a basic auth implementation + */ +var PasswordAuthorization = function(name, username, password) { + this.name = name; + this.username = username; + this.password = password; + this._btoa = null; + + this.foo = function() {}; + + if (typeof window !== 'undefined') + return this._btoa = btoa; + else + return this._btoa = require("btoa"); +}; + +PasswordAuthorization.prototype.apply = function(obj, authorizations) { + obj.headers["Authorization"] = "Basic " + this._btoa(this.username + ":" + this.password); + return true; +}; + +if(typeof exports !== 'undefined') { + exports.SwaggerAuthorizations = SwaggerAuthorizations; + exports.SwaggerHttp = SwaggerHttp; + exports.JQueryHttpClient = JQueryHttpClient; + exports.ShredHttpClient = ShredHttpClient; + exports.PasswordAuthorization = PasswordAuthorization; +} +else if (typeof window != 'undefined') { +/* + window.SwaggerApi = SwaggerApi; + window.SwaggerResource = SwaggerResource; + window.SwaggerOperation = SwaggerOperation; + window.SwaggerModelProperty = SwaggerModelProperty; + window.ApiKeyAuthorization = ApiKeyAuthorization; + window.PasswordAuthorization = PasswordAuthorization; +*/ + + this.SwaggerHttp = SwaggerHttp; + this.SwaggerRequest = SwaggerRequest; + this.authorizations = new SwaggerAuthorizations(); + this.JQueryHttpClient = JQueryHttpClient; + this.ShredHttpClient = ShredHttpClient; +}; + + (function() { - var ApiKeyAuthorization, PasswordAuthorization, SwaggerApi, SwaggerAuthorizations, SwaggerHttp, SwaggerModel, SwaggerModelProperty, SwaggerOperation, SwaggerRequest, SwaggerResource, log, + var SwaggerApi, SwaggerAuthorizations, SwaggerModel, SwaggerModelProperty, SwaggerOperation, SwaggerRequest, SwaggerResource, log, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; @@ -863,7 +1308,8 @@ } } } - req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this); + + req = new window.SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this); if (opts.mock != null) { return req; } else { @@ -966,515 +1412,9 @@ })(); - SwaggerRequest = (function() { - function SwaggerRequest(type, url, params, opts, successCallback, errorCallback, operation, execution) { - var body, e, fields, headers, key, myHeaders, name, obj, param, parent, possibleParams, requestContentType, responseContentType, status, urlEncoded, value, values, - _this = this; - this.type = type; - this.url = url; - this.params = params; - this.opts = opts; - this.successCallback = successCallback; - this.errorCallback = errorCallback; - this.operation = operation; - this.execution = execution; - if (this.type == null) { - throw "SwaggerRequest type is required (get/post/put/delete)."; - } - if (this.url == null) { - throw "SwaggerRequest url is required."; - } - if (this.successCallback == null) { - throw "SwaggerRequest successCallback is required."; - } - if (this.errorCallback == null) { - throw "SwaggerRequest error callback is required."; - } - if (this.operation == null) { - throw "SwaggerRequest operation is required."; - } - this.type = this.type.toUpperCase(); - headers = params.headers; - myHeaders = {}; - body = params.body; - parent = params["parent"]; - requestContentType = "application/json"; - if (body && (this.type === "POST" || this.type === "PUT" || this.type === "PATCH")) { - if (this.opts.requestContentType) { - requestContentType = this.opts.requestContentType; - } - } else { - if (((function() { - var _i, _len, _ref, _results; - _ref = this.operation.parameters; - _results = []; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - param = _ref[_i]; - if (param.paramType === "form") { - _results.push(param); - } - } - return _results; - }).call(this)).length > 0) { - type = param.type || param.dataType; - if (((function() { - var _i, _len, _ref, _results; - _ref = this.operation.parameters; - _results = []; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - param = _ref[_i]; - if (typeof type !== 'undefined' && type.toLowerCase() === "file") { - _results.push(param); - } - } - return _results; - }).call(this)).length > 0) { - requestContentType = "multipart/form-data"; - } else { - requestContentType = "application/x-www-form-urlencoded"; - } - } else if (this.type !== "DELETE") { - requestContentType = null; - } - } - if (requestContentType && this.operation.consumes) { - if (this.operation.consumes[requestContentType] === 'undefined') { - log("server doesn't consume " + requestContentType + ", try " + JSON.stringify(this.operation.consumes)); - if (this.requestContentType === null) { - requestContentType = this.operation.consumes[0]; - } - } - } - responseContentType = null; - if (this.type === "POST" || this.type === "GET" || this.type === "PATCH") { - if (this.opts.responseContentType) { - responseContentType = this.opts.responseContentType; - } else { - responseContentType = "application/json"; - } - } else { - responseContentType = null; - } - if (responseContentType && this.operation.produces) { - if (this.operation.produces[responseContentType] === 'undefined') { - log("server can't produce " + responseContentType); - } - } - if (requestContentType && requestContentType.indexOf("application/x-www-form-urlencoded") === 0) { - fields = {}; - possibleParams = (function() { - var _i, _len, _ref, _results; - _ref = this.operation.parameters; - _results = []; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - param = _ref[_i]; - if (param.paramType === "form") { - _results.push(param); - } - } - return _results; - }).call(this); - values = {}; - for (key in possibleParams) { - value = possibleParams[key]; - if (this.params[value.name]) { - values[value.name] = this.params[value.name]; - } - } - urlEncoded = ""; - for (key in values) { - value = values[key]; - if (urlEncoded !== "") { - urlEncoded += "&"; - } - urlEncoded += encodeURIComponent(key) + '=' + encodeURIComponent(value); - } - body = urlEncoded; - } - for (name in headers) { - myHeaders[name] = headers[name]; - } - if (requestContentType) { - myHeaders["Content-Type"] = requestContentType; - } - if (responseContentType) { - myHeaders["Accept"] = responseContentType; - } - if (!((headers != null) && (headers.mock != null))) { - obj = { - url: this.url, - method: this.type, - headers: myHeaders, - body: body, - useJQuery: this.useJQuery, - on: { - error: function(response) { - return _this.errorCallback(response, _this.opts.parent); - }, - redirect: function(response) { - return _this.successCallback(response, _this.opts.parent); - }, - 307: function(response) { - return _this.successCallback(response, _this.opts.parent); - }, - response: function(response) { - return _this.successCallback(response, _this.opts.parent); - } - } - }; - e = {}; - if (typeof window !== 'undefined') { - e = window; - } else { - e = exports; - } - status = e.authorizations.apply(obj, this.operation.authorizations); - if (opts.mock == null) { - if (status !== false) { - new SwaggerHttp().execute(obj); - } else { - obj.canceled = true; - } - } else { - return obj; - } - } - } - - SwaggerRequest.prototype.asCurl = function() { - var header_args, k, v; - header_args = (function() { - var _ref, _results; - _ref = this.headers; - _results = []; - for (k in _ref) { - v = _ref[k]; - _results.push("--header \"" + k + ": " + v + "\""); - } - return _results; - }).call(this); - return "curl " + (header_args.join(" ")) + " " + this.url; - }; - - return SwaggerRequest; - - })(); - - SwaggerHttp = (function() { - function SwaggerHttp() {} - - SwaggerHttp.prototype.Shred = null; - - SwaggerHttp.prototype.shred = null; - - SwaggerHttp.prototype.content = null; - - SwaggerHttp.prototype.initShred = function() { - var identity, toString, - _this = this; - if (typeof window !== 'undefined') { - this.Shred = require("./shred"); - } else { - this.Shred = require("shred"); - } - this.shred = new this.Shred(); - identity = function(x) { - return x; - }; - toString = function(x) { - return x.toString(); - }; - if (typeof window !== 'undefined') { - this.content = require("./shred/content"); - return this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], { - parser: identity, - stringify: toString - }); - } else { - return this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], { - parser: identity, - stringify: toString - }); - } - }; - - SwaggerHttp.prototype.execute = function(obj) { - if (this.isIE() || obj.useJQuery) { - return this.executeWithJQuery(obj); - } else { - return this.executeWithShred(obj); - } - }; - - SwaggerHttp.prototype.executeWithShred = function(obj) { - var cb, res, - _this = this; - if (!this.Shred) { - this.initShred(); - } - cb = obj.on; - res = { - error: function(raw) { - var headers, out; - if (obj) { - headers = raw._headers; - out = { - headers: headers, - url: raw.request.url, - method: raw.request.method, - status: raw.status, - data: raw.content.data - }; - return cb.error(out); - } - }, - redirect: function(raw) { - var headers, out; - if (obj) { - headers = raw._headers; - out = { - headers: headers, - url: raw.request.url, - method: raw.request.method, - status: raw.status, - data: raw.content.data - }; - return cb.redirect(out); - } - }, - 307: function(raw) { - var headers, out; - if (obj) { - headers = raw._headers; - out = { - headers: headers, - url: raw.request.url, - method: raw.request.method, - status: raw.status, - data: raw.content.data - }; - return cb.redirect(out); - } - }, - response: function(raw) { - var headers, out; - if (obj) { - headers = raw._headers; - out = { - headers: headers, - url: raw.request.url, - method: raw.request.method, - status: raw.status, - data: raw.content.data - }; - return cb.response(out); - } - } - }; - if (obj) { - obj.on = res; - } - return this.shred.request(obj); - }; - - SwaggerHttp.prototype.executeWithJQuery = function(obj) { - var beforeSend, cb, request, - _this = this; - cb = obj.on; - request = obj; - obj.type = obj.method; - obj.cache = false; - beforeSend = function(xhr) { - var key, _results; - if (obj.headers) { - _results = []; - for (key in obj.headers) { - if (key.toLowerCase() === "content-type") { - _results.push(obj.contentType = obj.headers[key]); - } else if (key.toLowerCase() === "accept") { - _results.push(obj.accepts = obj.headers[key]); - } else { - _results.push(xhr.setRequestHeader(key, obj.headers[key])); - } - } - return _results; - } - }; - obj.beforeSend = beforeSend; - obj.data = obj.body; - obj.complete = function(response, textStatus, opts) { - var headerArray, headers, i, out, _i, _j, _k, _ref, _ref1, _ref2, _ref3, _results, _results1; - headers = {}; - headerArray = response.getAllResponseHeaders().split(":"); - for (i = _i = 0, _ref = headerArray.length / 2, _ref1 = 2.; _ref1 > 0 ? _i <= _ref : _i >= _ref; i = _i += _ref1) { - headers[headerArray[i]] = headerArray[i + 1]; - } - out = { - headers: headers, - url: request.url, - method: request.method, - status: response.status, - data: response.responseText, - headers: headers - }; - if (_ref2 = response.status, __indexOf.call((function() { - _results = []; - for (_j = 200; _j <= 299; _j++){ _results.push(_j); } - return _results; - }).apply(this), _ref2) >= 0) { - cb.response(out); - } - if ((_ref3 = response.status, __indexOf.call((function() { - _results1 = []; - for (_k = 400; _k <= 599; _k++){ _results1.push(_k); } - return _results1; - }).apply(this), _ref3) >= 0) || response.status === 0) { - cb.error(out); - } - return cb.response(out); - }; - $.support.cors = true; - return $.ajax(obj); - }; - - SwaggerHttp.prototype.isIE = function() { - var isIE, nav, version; - ({ - isIE: false - }); - if (typeof navigator !== 'undefined' && navigator.userAgent) { - nav = navigator.userAgent.toLowerCase(); - if (nav.indexOf('msie') !== -1) { - version = parseInt(nav.split('msie')[1]); - if (version <= 8) { - isIE = true; - } - } - } - return isIE; - }; - - return SwaggerHttp; - - })(); - - SwaggerAuthorizations = (function() { - SwaggerAuthorizations.prototype.authz = null; - - function SwaggerAuthorizations() { - this.authz = {}; - } - - SwaggerAuthorizations.prototype.add = function(name, auth) { - this.authz[name] = auth; - return auth; - }; - - SwaggerAuthorizations.prototype.remove = function(name) { - return delete this.authz[name]; - }; - - SwaggerAuthorizations.prototype.apply = function(obj, authorizations) { - var key, result, status, value, _ref; - status = null; - _ref = this.authz; - for (key in _ref) { - value = _ref[key]; - result = value.apply(obj, authorizations); - if (result === false) { - status = false; - } - if (result === true) { - status = true; - } - } - return status; - }; - - return SwaggerAuthorizations; - - })(); - - ApiKeyAuthorization = (function() { - ApiKeyAuthorization.prototype.type = null; - - ApiKeyAuthorization.prototype.name = null; - - ApiKeyAuthorization.prototype.value = null; - - function ApiKeyAuthorization(name, value, type) { - this.name = name; - this.value = value; - this.type = type; - } - - ApiKeyAuthorization.prototype.apply = function(obj, authorizations) { - if (this.type === "query") { - if (obj.url.indexOf('?') > 0) { - obj.url = obj.url + "&" + this.name + "=" + this.value; - } else { - obj.url = obj.url + "?" + this.name + "=" + this.value; - } - return true; - } else if (this.type === "header") { - obj.headers[this.name] = this.value; - return true; - } - }; - - return ApiKeyAuthorization; - - })(); - - PasswordAuthorization = (function() { - PasswordAuthorization._btoa = null; - - PasswordAuthorization.prototype.name = null; - - PasswordAuthorization.prototype.username = null; - - PasswordAuthorization.prototype.password = null; - - function PasswordAuthorization(name, username, password) { - this.name = name; - this.username = username; - this.password = password; - PasswordAuthorization._ensureBtoa(); - } - - PasswordAuthorization.prototype.apply = function(obj, authorizations) { - obj.headers["Authorization"] = "Basic " + PasswordAuthorization._btoa(this.username + ":" + this.password); - return true; - }; - - PasswordAuthorization._ensureBtoa = function() { - if (typeof window !== 'undefined') { - return this._btoa = btoa; - } else { - return this._btoa = require("btoa"); - } - }; - - return PasswordAuthorization; - - })(); - this.SwaggerApi = SwaggerApi; - this.SwaggerResource = SwaggerResource; - this.SwaggerOperation = SwaggerOperation; - - this.SwaggerRequest = SwaggerRequest; - this.SwaggerModelProperty = SwaggerModelProperty; - - this.ApiKeyAuthorization = ApiKeyAuthorization; - this.PasswordAuthorization = PasswordAuthorization; - - this.SwaggerHttp = SwaggerHttp; - - this.authorizations = new SwaggerAuthorizations(); - }).call(this); diff --git a/src/swagger.coffee b/src/swagger.coffee deleted file mode 100644 index 0a8d22325..000000000 --- a/src/swagger.coffee +++ /dev/null @@ -1,1075 +0,0 @@ -log = -> - if window.console then console.log.apply console,arguments - -class SwaggerApi - - # Defaults - url: "http://api.wordnik.com/v4/resources.json" - debug: false - basePath: null - authorizations: null - authorizationScheme: null - info: null - useJQuery: null - - constructor: (url, options={}) -> - # if url is a hash, assume only options were passed - - if url - if url.url - options = url - else - @url = url - else - options = url - @url = options.url if options.url? - - @success = options.success if options.success? - @failure = if options.failure? then options.failure else -> - @progress = if options.progress? then options.progress else -> - - # Build right away if a callback was passed to the initializer - @build() if options.success? - - build: -> - @progress 'fetching resource list: ' + @url - obj = - useJQuery: @useJQuery - url: @url - method: "get" - headers: { - accept:"application/json" - } - on: - error: (response) => - if @url.substring(0, 4) isnt 'http' - @fail 'Please specify the protocol for ' + @url - else if response.status == 0 - @fail 'Can\'t read from server. It may not have the appropriate access-control-origin settings.' - else if response.status == 404 - @fail 'Can\'t read swagger JSON from ' + @url - else - @fail response.status + ' : ' + response.statusText + ' ' + @url - response: (response) => - responseObj = JSON.parse(response.data) - @swaggerVersion = responseObj.swaggerVersion - - if @swaggerVersion is "1.2" - @buildFromSpec responseObj - else - @buildFrom1_1Spec responseObj - - # apply authorizations - e = {} - if typeof window != 'undefined' - e = window - else - e = exports - e.authorizations.apply obj - - new SwaggerHttp().execute obj - @ - - # build the spec - buildFromSpec: (response)-> - @apiVersion = response.apiVersion if response.apiVersion? - @apis = {} - @apisArray = [] - @produces = response.produces - @authSchemes = response.authorizations - @info = response.info if response.info? - - # if apis.operations exists, this is an api declaration as opposed to a resource listing - isApi = false - for api in response.apis - if api.operations - for operation in api.operations - isApi = true - - # The base path derived from url - if response.basePath - # support swagger 1.1, which has basePath - @basePath = response.basePath - else if @url.indexOf('?') > 0 - @basePath = @url.substring(0, @url.lastIndexOf('?')) - else - @basePath = @url - - if isApi - newName = response.resourcePath.replace(/\//g,'') - this.resourcePath = response.resourcePath - - res = new SwaggerResource response, this - @apis[newName] = res - @apisArray.push res - else - for resource in response.apis - res = new SwaggerResource resource, this - @apis[res.name] = res - @apisArray.push res - if this.success - this.success() - this - - - buildFrom1_1Spec: (response)-> - log "This API is using a deprecated version of Swagger! Please see http://github.com/wordnik/swagger-core/wiki for more info" - @apiVersion = response.apiVersion if response.apiVersion? - @apis = {} - @apisArray = [] - @produces = response.produces - @info = response.info if response.info? - - # if apis.operations exists, this is an api declaration as opposed to a resource listing - isApi = false - for api in response.apis - if api.operations - for operation in api.operations - isApi = true - - # The base path derived from url - if response.basePath - # support swagger 1.1, which has basePath - @basePath = response.basePath - else if @url.indexOf('?') > 0 - @basePath = @url.substring(0, @url.lastIndexOf('?')) - else - @basePath = @url - - if isApi - newName = response.resourcePath.replace(/\//g,'') - this.resourcePath = response.resourcePath - - res = new SwaggerResource response, this - @apis[newName] = res - @apisArray.push res - else - for resource in response.apis - res = new SwaggerResource resource, this - @apis[res.name] = res - @apisArray.push res - if this.success - this.success() - this - - # This method is called each time a child resource finishes loading - # - selfReflect: -> - return false unless @apis? - for resource_name, resource of @apis - return false unless resource.ready? - - @setConsolidatedModels() - @ready = true - @success() if @success? - - fail: (message) -> - @failure message - throw message - - # parses models in all apis and sets a unique consolidated list of models - setConsolidatedModels: -> - @modelsArray = [] - @models = {} - for resource_name, resource of @apis - for modelName of resource.models - if not @models[modelName]? - @models[modelName] = resource.models[modelName] - @modelsArray.push resource.models[modelName] - for model in @modelsArray - model.setReferencedModels(@models) - - help: -> - for resource_name, resource of @apis - log resource_name - for operation_name, operation of resource.operations - log " #{operation.nickname}" - for parameter in operation.parameters - log " #{parameter.name}#{if parameter.required then ' (required)' else ''} - #{parameter.description}" - @ - -class SwaggerResource - api: null - produces: null - consumes: null - - constructor: (resourceObj, @api) -> - this.api = @api - produces = [] - consumes = [] - - @path = if @api.resourcePath? then @api.resourcePath else resourceObj.path - - @description = resourceObj.description - - # Extract name from path - # '/foo/dogs.format' -> 'dogs' - parts = @path.split("/") - @name = parts[parts.length - 1].replace('.{format}', '') - - # set the basePath to be the one in API. If response from server for this resource - # has a more specific one, we'll set it again there. - @basePath = @api.basePath - - # We're going to store operations in a map (operations) and a list (operationsArray) - @operations = {} - @operationsArray = [] - - # We're going to store models in a map (models) and a list (modelsArray) - @modelsArray = [] - @models = {} - @rawModels = {} - - if resourceObj.apis? and @api.resourcePath? - # read resource directly from operations object - @addApiDeclaration(resourceObj) - - else - # read from server - @api.fail "SwaggerResources must have a path." unless @path? - - # e.g."http://api.wordnik.com/v4/word.json" - - if @path.substring(0,4) == 'http' - # user absolute path - @url = @path.replace('{format}', 'json') - else - @url = @api.basePath + @path.replace('{format}', 'json') - - @api.progress 'fetching resource ' + @name + ': ' + @url - obj = - url: @url - method: "get" - useJQuery: @useJQuery - headers: { - accept:"application/json" - } - on: - error: (response) => - @api.fail "Unable to read api '" + @name + "' from path " + @url + " (server returned " + response.statusText + ")" - response: (response) => - responseObj = JSON.parse(response.data) - @addApiDeclaration(responseObj) - - # apply authorizations - e = {} - if typeof window != 'undefined' - e = window - else - e = exports - e.authorizations.apply obj - - new SwaggerHttp().execute obj - - # Constructs an absolute resource's basePath from relative one, using the @api basePath - # eg. if the @api.basePath = http://myhost.com:8090/mywebapp/v0/api-docs - # and the resource response contains a relative basePath='v0' - # then the function will return 'http://myhost.com:8090/mywebapp/v0' - getAbsoluteBasePath: (relativeBasePath) -> - url = @api.basePath - # first check if the base is a part of given url - pos = url.lastIndexOf(relativeBasePath) - if pos is -1 - # take the protocol, host and port parts only and glue the 'relativeBasePath' - parts = url.split("/") - url = parts[0] + "//" + parts[2] - if relativeBasePath.indexOf("/") is 0 - url + relativeBasePath - else - url + "/" + relativeBasePath - else if (relativeBasePath is "/") - url.substring(0, pos) - else - url.substring(0, pos) + relativeBasePath - - addApiDeclaration: (response) -> - if response.produces? - @produces = response.produces - if response.consumes? - @consumes = response.consumes - - # If there is a basePath in response, use that or else use - # the one from the api object - if response.basePath? and response.basePath.replace(/\s/g,'').length > 0 - @basePath = if response.basePath.indexOf("http") is -1 then @getAbsoluteBasePath(response.basePath) else response.basePath - - @addModels(response.models) - - # Instantiate SwaggerOperations and store them in the @operations map and @operationsArray - if response.apis - for endpoint in response.apis - @addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces) - - # Store a named reference to this resource on the parent object - @api[this.name] = this - - # Mark as ready - @ready = true - - # Now that this resource is loaded, tell the API to check in on itself - @api.selfReflect() - - addModels: (models) -> - if models? - for modelName of models - if not @models[modelName]? - swaggerModel = new SwaggerModel(modelName, models[modelName]) - @modelsArray.push swaggerModel - @models[modelName] = swaggerModel - @rawModels[modelName] = models[modelName]; - for model in @modelsArray - model.setReferencedModels(@models) - - - addOperations: (resource_path, ops, consumes, produces) -> - if ops - for o in ops - consumes = @consumes - produces = @produces - - if o.consumes? - consumes = o.consumes - else - consumes = @consumes - - if o.produces? - produces = o.produces - else - produces = @produces - - type = o.type || o.responseClass - if(type is "array") - ref = null - if o.items - ref = o.items["type"] || o.items["$ref"] - type = "array[" + ref + "]" - - responseMessages = o.responseMessages - method = o.method - - # support old httpMethod - if o.httpMethod - method = o.httpMethod - - # support old naming - if o.supportedContentTypes - consumes = o.supportedContentTypes - - # support old error responses - if o.errorResponses - responseMessages = o.errorResponses - for r in responseMessages - r.message = r.reason - r.reason = null - - # sanitize the nickname - o.nickname = @sanitize o.nickname - - op = new SwaggerOperation o.nickname, resource_path, method, o.parameters, o.summary, o.notes, type, responseMessages, this, consumes, produces, o.authorizations - @operations[op.nickname] = op - @operationsArray.push op - - sanitize: (nickname) -> - # allow only _a-zA-Z0-9 - op = nickname.replace /[\s!@#$%^&*()_+=\[{\]};:<>|./?,\\'""-]/g, '_' - # trim multiple underscores to one - op = op.replace /((_){2,})/g, '_' - # ditch leading underscores - op = op.replace /^(_)*/g, '' - # ditch trailing underscores - op = op.replace /([_])*$/g, '' - op - - help: -> - for operation_name, operation of @operations - msg = " #{operation.nickname}" - for parameter in operation.parameters - msg.concat(" #{parameter.name}#{if parameter.required then ' (required)' else ''} - #{parameter.description}") - msg - - -class SwaggerModel - constructor: (modelName, obj) -> - @name = if obj.id? then obj.id else modelName - @properties = [] - for propertyName of obj.properties - if obj.required? - for value of obj.required - if propertyName is obj.required[value] - obj.properties[propertyName].required = true - prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName]) - @properties.push prop - # support the 1.2 spec for required fields - - - # Set models referenced bu this model - setReferencedModels: (allModels) -> - for prop in @properties - type = prop.type || prop.dataType - if allModels[type]? - prop.refModel = allModels[type] - else if prop.refDataType? and allModels[prop.refDataType]? - prop.refModel = allModels[prop.refDataType] - - getMockSignature: (modelsToIgnore) -> - propertiesStr = [] - for prop in @properties - propertiesStr.push prop.toString() - - strong = ''; - stronger = ''; - strongClose = ''; - classOpen = strong + @name + ' {' + strongClose - classClose = strong + '}' + strongClose - returnVal = classOpen + '
' + propertiesStr.join(',
') + '
' + classClose - - # create the array if necessary and then add the current element - if !modelsToIgnore - modelsToIgnore = [] - modelsToIgnore.push(@) - - # iterate thru all properties and add models which are not in modelsToIgnore - # modelsToIgnore is used to ensure that recursive references do not lead to endless loop - # and that the same model is not displayed multiple times - for prop in @properties - if(prop.refModel? and modelsToIgnore.indexOf(prop.refModel) == -1) - returnVal = returnVal + ('
' + prop.refModel.getMockSignature(modelsToIgnore)) - - returnVal - - createJSONSample: (modelsToIgnore) -> - result = {} - modelsToIgnore = modelsToIgnore || []; - modelsToIgnore.push(@name); - for prop in @properties - result[prop.name] = prop.getSampleValue(modelsToIgnore) - modelsToIgnore.pop(@name); - result - -class SwaggerModelProperty - constructor: (@name, obj) -> - @dataType = obj.type || obj.dataType || obj["$ref"] - @isCollection = @dataType && (@dataType.toLowerCase() is 'array' || @dataType.toLowerCase() is 'list' || - @dataType.toLowerCase() is 'set'); - @descr = obj.description - @required = obj.required - - if obj.items? - if obj.items.type? then @refDataType = obj.items.type - if obj.items.$ref? then @refDataType = obj.items.$ref - @dataTypeWithRef = if @refDataType? then (@dataType + '[' + @refDataType + ']') else @dataType - if obj.allowableValues? - @valueType = obj.allowableValues.valueType - @values = obj.allowableValues.values - if @values? - @valuesString = "'" + @values.join("' or '") + "'" - if obj.enum? - @valueType = "string" - @values = obj.enum - if @values? - @valueString = "'" + @values.join("' or '") + "'" - - getSampleValue: (modelsToIgnore) -> - if(@refModel? and (modelsToIgnore[@refModel.name] is 'undefined')) - result = @refModel.createJSONSample(modelsToIgnore) - else - if @isCollection - result = @toSampleValue @refDataType - else - result = @toSampleValue @dataType - if @isCollection then [result] else result - - toSampleValue: (value) -> - if value is "integer" - result = 0 - else if value is "boolean" - result = false - else if value is "double" - result = 0.0 - else if value is "string" - result = "" - else - result = value - result - - toString: -> - req = if @required then 'propReq' else 'propOpt' - - str = '' + @name + ' (' + @dataTypeWithRef + ''; - if !@required - str += ', optional' - - str += ')'; - if @values? - str += " = ['" + @values.join("' or '") + "']" - - if @descr? - str += ': ' + @descr + '' - - str - -# SwaggerOperation converts an operation into a method which can be executed directly -class SwaggerOperation - constructor: (@nickname, @path, @method, @parameters=[], @summary, @notes, @type, @responseMessages, @resource, @consumes, @produces, @authorizations) -> - @resource.api.fail "SwaggerOperations must have a nickname." unless @nickname? - @resource.api.fail "SwaggerOperation #{nickname} is missing path." unless @path? - @resource.api.fail "SwaggerOperation #{nickname} is missing method." unless @method? - - # Convert {format} to 'json' - @path = @path.replace('{format}', 'json') - @method = @method.toLowerCase() - @isGetMethod = @method == "get" - @resourceName = @resource.name - - # if void clear it - if(@type?.toLowerCase() is 'void') then @type = undefined - if @type? - # set the signature of response class - @responseClassSignature = @getSignature(@type, @resource.models) - @responseSampleJSON = @getSampleJSON(@type, @resource.models) - - @responseMessages = @responseMessages || [] - - for parameter in @parameters - # Path params do not have a name, set the name to the path if name is n/a - parameter.name = parameter.name || parameter.type || parameter.dataType - - type = parameter.type || parameter.dataType - - if(type.toLowerCase() is 'boolean') - parameter.allowableValues = {} - parameter.allowableValues.values = ["true", "false"] - - parameter.signature = @getSignature(type, @resource.models) - parameter.sampleJSON = @getSampleJSON(type, @resource.models) - - if parameter.enum? - parameter.isList = true - # set the values - parameter.allowableValues = {} - parameter.allowableValues.descriptiveValues = [] - for v in parameter.enum - if parameter.defaultValue? and parameter.defaultValue == v - parameter.allowableValues.descriptiveValues.push {value: String(v), isDefault: true} - else - parameter.allowableValues.descriptiveValues.push {value: String(v), isDefault: false} - - # Set allowableValue attributes for 1.1 spec - if parameter.allowableValues? - # Set isRange and isList flags on param - if parameter.allowableValues.valueType == "RANGE" - parameter.isRange = true - else - parameter.isList = true - - # Set a descriptive values on allowable values - # This contains value and isDefault flag for each value - if parameter.allowableValues.values? - parameter.allowableValues.descriptiveValues = [] - for v in parameter.allowableValues.values - if parameter.defaultValue? and parameter.defaultValue == v - parameter.allowableValues.descriptiveValues.push {value: v, isDefault: true} - else - parameter.allowableValues.descriptiveValues.push {value: v, isDefault: false} - - - # Store a named reference to this operation on the parent resource - # getDefinitions() maps to getDefinitionsData.do() - @resource[@nickname]= (args, callback, error) => - @do(args, callback, error) - - # shortcut to help method - @resource[@nickname].help = => - @help() - - isListType: (type) -> - if(type.indexOf('[') >= 0) then type.substring(type.indexOf('[') + 1, type.indexOf(']')) else undefined - - getSignature: (type, models) -> - # set listType if it exists - listType = @isListType(type) - - # set flag which says if its primitive or not - isPrimitive = if ((listType? and models[listType]) or models[type]?) then false else true - - if (isPrimitive) then type else (if listType? then models[listType].getMockSignature() else models[type].getMockSignature()) - - getSampleJSON: (type, models) -> - # set listType if it exists - listType = @isListType(type) - - # set flag which says if its primitive or not - isPrimitive = if ((listType? and models[listType]) or models[type]?) then false else true - - val = if (isPrimitive) then undefined else (if listType? then models[listType].createJSONSample() else models[type].createJSONSample()) - - # pretty printing obtained JSON - if val - # if container is list wrap it - val = if listType then [val] else val - JSON.stringify(val, null, 2) - - do: (args={}, opts={}, callback, error) => - requestContentType = null - responseContentType = null - - # if the args is a function, then it must be a resource without - # parameters or opts - if (typeof args) == "function" - error = opts - callback = args - args = {} - - if (typeof opts) == "function" - error = callback - callback = opts - - # Define a default error handler - unless error? - error = (xhr, textStatus, error) -> - log xhr, textStatus, error - - # Define a default success handler - unless callback? - callback = (response) -> - content = null - if response? - content = response.data - else - content = "no data" - log "default callback: " + content - - # params to pass into the request - params = {} - params.headers = [] - - # Pull headers out of args - if args.headers? - params.headers = args.headers - delete args.headers - - for param in @parameters when (param.paramType is "header" ) - if args[param.name] - params.headers[param.name] = args[param.name] - - # Pull body out of args - if args.body? - params.body = args.body - delete args.body - - # pull out any form params - possibleParams = (param for param in @parameters when (param.paramType is "form" or param.paramType.toLowerCase() is "file" )) - if possibleParams - for key, value of possibleParams - if args[value.name] - params[value.name] = args[value.name] - - req = new SwaggerRequest(@method, @urlify(args), params, opts, callback, error, this) - if opts.mock? - req - else - true - - pathJson: -> @path.replace "{format}", "json" - - pathXml: -> @path.replace "{format}", "xml" - - # converts the operation path into a real URL, and appends query params - urlify: (args) -> - url = @resource.basePath + @pathJson() - - # Iterate over allowable params, interpolating the 'path' params into the url string. - # Whatever's left over in the args object will become the query string - for param in @parameters - if param.paramType == 'path' - if args[param.name] - reg = new RegExp '\{'+param.name+'[^\}]*\}', 'gi' - url = url.replace(reg, encodeURIComponent(args[param.name])) - delete args[param.name] - else - throw "#{param.name} is a required path param." - - # Append the query string to the URL - queryParams = "" - for param in @parameters - if param.paramType == 'query' - if args[param.name] - if queryParams != "" - queryParams += "&" - queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]) - - url += ("?" + queryParams) if queryParams? and queryParams.length > 0 - - url - - # expose default headers - supportHeaderParams: -> - @resource.api.supportHeaderParams - - # expose supported submit methods - supportedSubmitMethods: -> - @resource.api.supportedSubmitMethods - - getQueryParams: (args) -> - @getMatchingParams ['query'], args - - getHeaderParams: (args) -> - @getMatchingParams ['header'], args - - # From args extract params of paramType and return them - getMatchingParams: (paramTypes, args) -> - matchingParams = {} - for param in @parameters - if args and args[param.name] - matchingParams[param.name] = args[param.name] - - for name, value of @resource.api.headers - matchingParams[name] = value - - matchingParams - - help: -> - msg = "" - for parameter in @parameters - if msg isnt "" then msg += "\n" - msg += "* #{parameter.name}#{if parameter.required then ' (required)' else ''} - #{parameter.description}" - msg - - -# Swagger Request turns an operation into an actual request -class SwaggerRequest - constructor: (@type, @url, @params, @opts, @successCallback, @errorCallback, @operation, @execution) -> - throw "SwaggerRequest type is required (get/post/put/delete)." unless @type? - throw "SwaggerRequest url is required." unless @url? - throw "SwaggerRequest successCallback is required." unless @successCallback? - throw "SwaggerRequest error callback is required." unless @errorCallback? - throw "SwaggerRequest operation is required." unless @operation? - - @type = @type.toUpperCase() - headers = params.headers - myHeaders = {} - body = params.body - parent = params["parent"] - - requestContentType = "application/json" - # if post or put, set the content-type being sent, otherwise make it null - # some servers will die if content-type is set but there is no body - if body and (@type is "POST" or @type is "PUT" or @type is "PATCH") - if @opts.requestContentType - requestContentType = @opts.requestContentType - else - # if any form params, content-type must be set - if (param for param in @operation.parameters when param.paramType is "form").length > 0 - type = param.type || param.dataType - if (param for param in @operation.parameters when typeof type isnt 'undefined' and type.toLowerCase() is "file").length > 0 - requestContentType = "multipart/form-data" - else - requestContentType = "application/x-www-form-urlencoded" - else if @type isnt "DELETE" - requestContentType = null - - # verify the content type is acceptable from what it defines - if requestContentType and @operation.consumes - if @operation.consumes[requestContentType] is 'undefined' - log "server doesn't consume " + requestContentType + ", try " + JSON.stringify(@operation.consumes) - if @requestContentType == null - requestContentType = @operation.consumes[0] - - responseContentType = null - # if get or post, set the content-type being sent, otherwise make it null - if (@type is "POST" or @type is "GET" or @type is "PATCH") - if @opts.responseContentType - responseContentType = @opts.responseContentType - else - responseContentType = "application/json" - else - responseContentType = null - - # verify the content type can be produced - if responseContentType and @operation.produces - if @operation.produces[responseContentType] is 'undefined' - log "server can't produce " + responseContentType - - # prepare the body from params, if needed - if requestContentType && requestContentType.indexOf("application/x-www-form-urlencoded") is 0 - # pull fields from args - fields = {} - possibleParams = (param for param in @operation.parameters when param.paramType is "form") - - values = {} - for key, value of possibleParams - if @params[value.name] - values[value.name] = @params[value.name] - urlEncoded = "" - for key, value of values - if urlEncoded != "" - urlEncoded += "&" - urlEncoded += encodeURIComponent(key) + '=' + encodeURIComponent(value) - body = urlEncoded - for name of headers - myHeaders[name] = headers[name] - if requestContentType - myHeaders["Content-Type"] = requestContentType - if responseContentType - myHeaders["Accept"] = responseContentType - - unless headers? and headers.mock? - obj = - url: @url - method: @type - headers: myHeaders - body: body - useJQuery: @useJQuery - on: - error: (response) => - @errorCallback response, @opts.parent - redirect: (response) => - @successCallback response, @opts.parent - 307: (response) => - @successCallback response, @opts.parent - response: (response) => - @successCallback response, @opts.parent - - # apply authorizations - e = {} - if typeof window != 'undefined' - e = window - else - e = exports - status = e.authorizations.apply obj, @operation.authorizations - - unless opts.mock? - if status isnt false - new SwaggerHttp().execute obj - else - obj.canceled = true - else - return obj - - asCurl: -> - header_args = ("--header \"#{k}: #{v}\"" for k,v of @headers) - "curl #{header_args.join(" ")} #{@url}" - -class SwaggerHttp - Shred: null - shred: null - content: null - - initShred: -> - if typeof window != 'undefined' - @Shred = require "./shred" - else - @Shred = require "shred" - @shred = new @Shred() - - identity = (x) => x - toString = (x) => x.toString() - - if typeof window != 'undefined' - @content = require "./shred/content" - @content.registerProcessor( - ["application/json; charset=utf-8","application/json","json"], - { - parser: (identity), - stringify: toString - } - ) - else - @Shred.registerProcessor( - ["application/json; charset=utf-8","application/json","json"], - { - parser: (identity), - stringify: toString - } - ) - - execute: (obj) -> - if @isIE() or obj.useJQuery - @executeWithJQuery obj - else - @executeWithShred obj - - executeWithShred: (obj) -> - if !@Shred - @initShred() - cb = obj.on - res = { - error: (raw) => - if obj - headers = raw._headers - out = { - headers: headers - url: raw.request.url - method: raw.request.method - status: raw.status - data: raw.content.data - } - cb.error out - redirect: (raw) => - if obj - headers = raw._headers - out = { - headers: headers - url: raw.request.url - method: raw.request.method - status: raw.status - data: raw.content.data - } - cb.redirect out - 307: (raw) => - if obj - headers = raw._headers - out = { - headers: headers - url: raw.request.url - method: raw.request.method - status: raw.status - data: raw.content.data - } - cb.redirect out - response: (raw) => - if obj - headers = raw._headers - out = { - headers: headers - url: raw.request.url - method: raw.request.method - status: raw.status - data: raw.content.data - } - cb.response out - } - if obj - obj.on = res - - @shred.request obj - - executeWithJQuery: (obj) -> - cb = obj.on - request = obj - obj.type = obj.method - obj.cache = false - - # set headers - beforeSend = (xhr) -> - if obj.headers - for key of obj.headers - if key.toLowerCase() is "content-type" - obj.contentType = obj.headers[key] - else if key.toLowerCase() is "accept" - obj.accepts = obj.headers[key] - else - xhr.setRequestHeader(key, obj.headers[key]) - - obj.beforeSend = beforeSend - obj.data = obj.body - - obj.complete = (response, textStatus, opts) => - headers = {} - headerArray = response.getAllResponseHeaders().split(":") - for i in [0..headerArray.length/2] by (2) - headers[headerArray[i]] = headerArray[i+1] - - out = { - headers: headers - url: request.url - method: request.method - status: response.status - data: response.responseText - headers: headers - } - if response.status in [200..299] - cb.response out - if response.status in [400..599] or response.status is 0 - cb.error out - cb.response out - $.support.cors = true - $.ajax(obj) - - isIE:() -> - isIE: false - if typeof navigator isnt 'undefined' and navigator.userAgent - nav = navigator.userAgent.toLowerCase() - if nav.indexOf('msie') isnt -1 - version = parseInt(nav.split('msie')[1]) - if version <= 8 - isIE = true - isIE - -class SwaggerAuthorizations - authz: null - - constructor: -> - @authz = {} - - add: (name, auth) -> - @authz[name] = auth - auth - - remove: (name) -> - delete @authz[name] - - apply: (obj, authorizations) -> - status = null - for key, value of @authz - # see if it applies - result = value.apply obj, authorizations - if result is false - status = false - if result is true - status = true - status - -class ApiKeyAuthorization - type: null - name: null - value: null - - constructor: (name, value, type) -> - @name = name - @value = value - @type = type - - apply: (obj, authorizations) -> - if @type == "query" - if obj.url.indexOf('?') > 0 - obj.url = obj.url + "&" + @name + "=" + @value - else - obj.url = obj.url + "?" + @name + "=" + @value - true - else if @type == "header" - obj.headers[@name] = @value - true - -class PasswordAuthorization - @_btoa: null - name: null - username: null - password: null - - constructor: (name, username, password) -> - @name = name - @username = username - @password = password - PasswordAuthorization._ensureBtoa() - - apply: (obj, authorizations) -> - obj.headers["Authorization"] = "Basic " + PasswordAuthorization._btoa(@username + ":" + @password) - true - - @_ensureBtoa: -> - if typeof window != 'undefined' - @_btoa = btoa - else - @_btoa = require "btoa" - -@SwaggerApi = SwaggerApi -@SwaggerResource = SwaggerResource -@SwaggerOperation = SwaggerOperation -@SwaggerRequest = SwaggerRequest -@SwaggerModelProperty = SwaggerModelProperty -@ApiKeyAuthorization = ApiKeyAuthorization -@PasswordAuthorization = PasswordAuthorization -@SwaggerHttp = SwaggerHttp - -@authorizations = new SwaggerAuthorizations() From 567adf0e32d2f7790584d7423aaad5a6b975d36a Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Mon, 10 Feb 2014 16:43:58 -0800 Subject: [PATCH 02/13] more clean-ups --- lib/swagger.js | 678 ++++++++++++++++++++++++------------------------- 1 file changed, 325 insertions(+), 353 deletions(-) diff --git a/lib/swagger.js b/lib/swagger.js index de9aa4f48..1f77c69d9 100644 --- a/lib/swagger.js +++ b/lib/swagger.js @@ -1,3 +1,317 @@ +var __bind = function(fn, me){ + return function(){ + return fn.apply(me, arguments); + }; +}; + +var SwaggerOperation = function(nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations) { + var parameter, v, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _ref3, + _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.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.consumes = consumes; + this.produces = produces; + this.authorizations = authorizations; + this["do"] = __bind(this["do"], this); + + if (errors.length > 0) + this.resource.api.fail(errors); + + this.path = this.path.replace('{format}', 'json'); + this.method = this.method.toLowerCase(); + this.isGetMethod = this.method === "get"; + + this.resourceName = this.resource.name; + if(typeof this.type !== 'undefined' && this.type === 'void') + this.type = null; + else { + this.responseClassSignature = this.getSignature(this.type, this.resource.models); + this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models); + } + + _ref1 = this.parameters; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + parameter = _ref1[_i]; + parameter.name = parameter.name || parameter.type || parameter.dataType; + type = parameter.type || parameter.dataType; + if (type.toLowerCase() === 'boolean') { + parameter.allowableValues = {}; + parameter.allowableValues.values = ["true", "false"]; + } + parameter.signature = this.getSignature(type, this.resource.models); + parameter.sampleJSON = this.getSampleJSON(type, this.resource.models); + if (parameter["enum"] != null) { + parameter.isList = true; + parameter.allowableValues = {}; + parameter.allowableValues.descriptiveValues = []; + _ref2 = parameter["enum"]; + for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { + v = _ref2[_j]; + if ((parameter.defaultValue != null) && parameter.defaultValue === v) { + parameter.allowableValues.descriptiveValues.push({ + value: String(v), + isDefault: true + }); + } else { + parameter.allowableValues.descriptiveValues.push({ + value: String(v), + isDefault: false + }); + } + } + } + if (parameter.allowableValues != null) { + if (parameter.allowableValues.valueType === "RANGE") { + parameter.isRange = true; + } else { + parameter.isList = true; + } + if (parameter.allowableValues.values != null) { + parameter.allowableValues.descriptiveValues = []; + _ref3 = parameter.allowableValues.values; + for (_k = 0, _len2 = _ref3.length; _k < _len2; _k++) { + v = _ref3[_k]; + if ((parameter.defaultValue != null) && parameter.defaultValue === v) { + parameter.allowableValues.descriptiveValues.push({ + value: v, + isDefault: true + }); + } else { + parameter.allowableValues.descriptiveValues.push({ + value: v, + isDefault: false + }); + } + } + } + } + } + this.resource[this.nickname] = function(args, callback, error) { + return _this["do"](args, callback, error); + }; + this.resource[this.nickname].help = function() { + return _this.help(); + }; +} + +SwaggerOperation.prototype.isListType = function(type) { + if (type.indexOf('[') >= 0) { + return type.substring(type.indexOf('[') + 1, type.indexOf(']')); + } else { + return void 0; + } +}; + +SwaggerOperation.prototype.getSignature = function(type, models) { + var isPrimitive, listType; + listType = this.isListType(type); + isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true; + if (isPrimitive) { + return type; + } else { + if (listType != null) { + return models[listType].getMockSignature(); + } else { + return models[type].getMockSignature(); + } + } +}; + +SwaggerOperation.prototype.getSampleJSON = function(type, models) { + var isPrimitive, listType, val; + listType = this.isListType(type); + isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true; + val = isPrimitive ? void 0 : (listType != null ? models[listType].createJSONSample() : models[type].createJSONSample()); + if (val) { + val = listType ? [val] : val; + return JSON.stringify(val, null, 2); + } +}; + +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") { + error = opts; + callback = args; + args = {}; + } + if ((typeof opts) === "function") { + error = callback; + callback = opts; + } + if (error == null) { + error = function(xhr, textStatus, error) { + return log(xhr, textStatus, error); + }; + } + if (callback == null) { + callback = function(response) { + var content; + content = null; + if (response != null) { + content = response.data; + } else { + content = "no data"; + } + return log("default callback: " + content); + }; + } + params = {}; + params.headers = []; + if (args.headers != null) { + params.headers = args.headers; + delete args.headers; + } + _ref = this.parameters; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + param = _ref[_i]; + if (param.paramType === "header") { + if (args[param.name]) { + params.headers[param.name] = args[param.name]; + } + } + } + if (args.body != null) { + params.body = args.body; + delete args.body; + } + possibleParams = (function() { + var _j, _len1, _ref1, _results; + _ref1 = this.parameters; + _results = []; + for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { + param = _ref1[_j]; + if (param.paramType === "form" || param.paramType.toLowerCase() === "file") { + _results.push(param); + } + } + return _results; + }).call(this); + if (possibleParams) { + for (key in possibleParams) { + value = possibleParams[key]; + if (args[value.name]) { + params[value.name] = args[value.name]; + } + } + } + + req = new window.SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this); + if (opts.mock != null) { + return req; + } else { + return true; + } +}; + +SwaggerOperation.prototype.pathJson = function() { + return this.path.replace("{format}", "json"); +}; + +SwaggerOperation.prototype.pathXml = function() { + return this.path.replace("{format}", "xml"); +}; + +SwaggerOperation.prototype.urlify = function(args) { + var param, queryParams, reg, url, _i, _j, _len, _len1, _ref, _ref1; + url = this.resource.basePath + this.pathJson(); + _ref = this.parameters; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + param = _ref[_i]; + if (param.paramType === 'path') { + if (args[param.name]) { + reg = new RegExp('\{' + param.name + '[^\}]*\}', 'gi'); + url = url.replace(reg, encodeURIComponent(args[param.name])); + delete args[param.name]; + } else { + throw "" + param.name + " is a required path param."; + } + } + } + queryParams = ""; + _ref1 = this.parameters; + for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { + param = _ref1[_j]; + if (param.paramType === 'query') { + if (args[param.name]) { + if (queryParams !== "") { + queryParams += "&"; + } + queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]); + } + } + } + if ((queryParams != null) && queryParams.length > 0) { + url += "?" + queryParams; + } + return url; +}; + +SwaggerOperation.prototype.supportHeaderParams = function() { + return this.resource.api.supportHeaderParams; +}; + +SwaggerOperation.prototype.supportedSubmitMethods = function() { + return this.resource.api.supportedSubmitMethods; +}; + +SwaggerOperation.prototype.getQueryParams = function(args) { + return this.getMatchingParams(['query'], args); +}; + +SwaggerOperation.prototype.getHeaderParams = function(args) { + return this.getMatchingParams(['header'], args); +}; + +SwaggerOperation.prototype.getMatchingParams = function(paramTypes, args) { + var matchingParams, name, param, value, _i, _len, _ref, _ref1; + matchingParams = {}; + _ref = this.parameters; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + param = _ref[_i]; + if (args && args[param.name]) { + matchingParams[param.name] = args[param.name]; + } + } + _ref1 = this.resource.api.headers; + for (name in _ref1) { + value = _ref1[name]; + matchingParams[name] = value; + } + return matchingParams; +}; + +SwaggerOperation.prototype.help = function() { + var msg, parameter, _i, _len, _ref; + msg = ""; + _ref = this.parameters; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + parameter = _ref[_i]; + if (msg !== "") { + msg += "\n"; + } + msg += "* " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description; + } + return msg; +}; + var SwaggerRequest = function(type, url, params, opts, successCallback, errorCallback, operation, execution) { var _this = this; var errors = []; @@ -16,18 +330,6 @@ var SwaggerRequest = function(type, url, params, opts, successCallback, errorCal throw errors; } - // if (this.type == null) - // throw "SwaggerRequest type is required (get/post/put/delete/patch/options)."; - // if (this.url == null) - // throw "SwaggerRequest url is required."; - // if (this.successCallback == null) - // throw "SwaggerRequest successCallback is required."; - // if (this.errorCallback == null) - // throw "SwaggerRequest error callback is required."; - // if (this.operation == null) - // throw "SwaggerRequest operation is required."; - - this.type = this.type.toUpperCase(); var myHeaders = {}; @@ -57,9 +359,9 @@ var SwaggerRequest = function(type, url, params, opts, successCallback, errorCal // if any form params, content type must be set if(formParams.length > 0) { if(fileParams.length > 0) - requestContentType = "application/x-www-form-urlencoded" + requestContentType = "multipart/form-data"; else - requestContentType = "multipart/form-data" + requestContentType = "application/x-www-form-urlencoded"; } else if (this.type != "DELETE") requestContentType = null; @@ -101,7 +403,7 @@ var SwaggerRequest = function(type, url, params, opts, successCallback, errorCal var encoded = ""; for(key in values) { - value = values[key]; + value = this.params[key]; if(encoded !== "") encoded += "&"; encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value); @@ -157,18 +459,13 @@ var SwaggerRequest = function(type, url, params, opts, successCallback, errorCal }; SwaggerRequest.prototype.asCurl = function() { - var header_args, k, v; - header_args = (function() { - var _ref, _results; - _ref = this.headers; - _results = []; - for (k in _ref) { - v = _ref[k]; - _results.push("--header \"" + k + ": " + v + "\""); + var results = []; + if(this.headers) { + for(key in this.headers) { + results.push("--header \"" + key + ": " + this.headers[v] + "\""); } - return _results; - }).call(this); - return "curl " + (header_args.join(" ")) + " " + this.url; + } + return "curl " + (results.join(" ")) + " " + this.url; }; /* @@ -427,20 +724,12 @@ if(typeof exports !== 'undefined') { exports.PasswordAuthorization = PasswordAuthorization; } else if (typeof window != 'undefined') { -/* - window.SwaggerApi = SwaggerApi; - window.SwaggerResource = SwaggerResource; - window.SwaggerOperation = SwaggerOperation; - window.SwaggerModelProperty = SwaggerModelProperty; - window.ApiKeyAuthorization = ApiKeyAuthorization; - window.PasswordAuthorization = PasswordAuthorization; -*/ - this.SwaggerHttp = SwaggerHttp; this.SwaggerRequest = SwaggerRequest; this.authorizations = new SwaggerAuthorizations(); this.JQueryHttpClient = JQueryHttpClient; this.ShredHttpClient = ShredHttpClient; + this.SwaggerOperation = SwaggerOperation; }; @@ -889,7 +1178,7 @@ else if (typeof window != 'undefined') { } } o.nickname = this.sanitize(o.nickname); - op = new SwaggerOperation(o.nickname, resource_path, method, o.parameters, o.summary, o.notes, type, responseMessages, this, consumes, produces, o.authorizations); + op = new window.SwaggerOperation(o.nickname, resource_path, method, o.parameters, o.summary, o.notes, type, responseMessages, this, consumes, produces, o.authorizations); this.operations[op.nickname] = op; _results.push(this.operationsArray.push(op)); } @@ -1096,325 +1385,8 @@ else if (typeof window != 'undefined') { })(); - SwaggerOperation = (function() { - function SwaggerOperation(nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations) { - var parameter, v, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _ref3, - _this = this; - this.nickname = nickname; - this.path = path; - this.method = method; - this.parameters = parameters != null ? parameters : []; - this.summary = summary; - this.notes = notes; - this.type = type; - this.responseMessages = responseMessages; - this.resource = resource; - this.consumes = consumes; - this.produces = produces; - this.authorizations = authorizations; - this["do"] = __bind(this["do"], this); - if (this.nickname == null) { - this.resource.api.fail("SwaggerOperations must have a nickname."); - } - if (this.path == null) { - this.resource.api.fail("SwaggerOperation " + nickname + " is missing path."); - } - if (this.method == null) { - this.resource.api.fail("SwaggerOperation " + nickname + " is missing method."); - } - this.path = this.path.replace('{format}', 'json'); - this.method = this.method.toLowerCase(); - this.isGetMethod = this.method === "get"; - this.resourceName = this.resource.name; - if (((_ref = this.type) != null ? _ref.toLowerCase() : void 0) === 'void') { - this.type = void 0; - } - if (this.type != null) { - this.responseClassSignature = this.getSignature(this.type, this.resource.models); - this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models); - } - this.responseMessages = this.responseMessages || []; - _ref1 = this.parameters; - for (_i = 0, _len = _ref1.length; _i < _len; _i++) { - parameter = _ref1[_i]; - parameter.name = parameter.name || parameter.type || parameter.dataType; - type = parameter.type || parameter.dataType; - if (type.toLowerCase() === 'boolean') { - parameter.allowableValues = {}; - parameter.allowableValues.values = ["true", "false"]; - } - parameter.signature = this.getSignature(type, this.resource.models); - parameter.sampleJSON = this.getSampleJSON(type, this.resource.models); - if (parameter["enum"] != null) { - parameter.isList = true; - parameter.allowableValues = {}; - parameter.allowableValues.descriptiveValues = []; - _ref2 = parameter["enum"]; - for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { - v = _ref2[_j]; - if ((parameter.defaultValue != null) && parameter.defaultValue === v) { - parameter.allowableValues.descriptiveValues.push({ - value: String(v), - isDefault: true - }); - } else { - parameter.allowableValues.descriptiveValues.push({ - value: String(v), - isDefault: false - }); - } - } - } - if (parameter.allowableValues != null) { - if (parameter.allowableValues.valueType === "RANGE") { - parameter.isRange = true; - } else { - parameter.isList = true; - } - if (parameter.allowableValues.values != null) { - parameter.allowableValues.descriptiveValues = []; - _ref3 = parameter.allowableValues.values; - for (_k = 0, _len2 = _ref3.length; _k < _len2; _k++) { - v = _ref3[_k]; - if ((parameter.defaultValue != null) && parameter.defaultValue === v) { - parameter.allowableValues.descriptiveValues.push({ - value: v, - isDefault: true - }); - } else { - parameter.allowableValues.descriptiveValues.push({ - value: v, - isDefault: false - }); - } - } - } - } - } - this.resource[this.nickname] = function(args, callback, error) { - return _this["do"](args, callback, error); - }; - this.resource[this.nickname].help = function() { - return _this.help(); - }; - } - - SwaggerOperation.prototype.isListType = function(type) { - if (type.indexOf('[') >= 0) { - return type.substring(type.indexOf('[') + 1, type.indexOf(']')); - } else { - return void 0; - } - }; - - SwaggerOperation.prototype.getSignature = function(type, models) { - var isPrimitive, listType; - listType = this.isListType(type); - isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true; - if (isPrimitive) { - return type; - } else { - if (listType != null) { - return models[listType].getMockSignature(); - } else { - return models[type].getMockSignature(); - } - } - }; - - SwaggerOperation.prototype.getSampleJSON = function(type, models) { - var isPrimitive, listType, val; - listType = this.isListType(type); - isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true; - val = isPrimitive ? void 0 : (listType != null ? models[listType].createJSONSample() : models[type].createJSONSample()); - if (val) { - val = listType ? [val] : val; - return JSON.stringify(val, null, 2); - } - }; - - 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") { - error = opts; - callback = args; - args = {}; - } - if ((typeof opts) === "function") { - error = callback; - callback = opts; - } - if (error == null) { - error = function(xhr, textStatus, error) { - return log(xhr, textStatus, error); - }; - } - if (callback == null) { - callback = function(response) { - var content; - content = null; - if (response != null) { - content = response.data; - } else { - content = "no data"; - } - return log("default callback: " + content); - }; - } - params = {}; - params.headers = []; - if (args.headers != null) { - params.headers = args.headers; - delete args.headers; - } - _ref = this.parameters; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - param = _ref[_i]; - if (param.paramType === "header") { - if (args[param.name]) { - params.headers[param.name] = args[param.name]; - } - } - } - if (args.body != null) { - params.body = args.body; - delete args.body; - } - possibleParams = (function() { - var _j, _len1, _ref1, _results; - _ref1 = this.parameters; - _results = []; - for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { - param = _ref1[_j]; - if (param.paramType === "form" || param.paramType.toLowerCase() === "file") { - _results.push(param); - } - } - return _results; - }).call(this); - if (possibleParams) { - for (key in possibleParams) { - value = possibleParams[key]; - if (args[value.name]) { - params[value.name] = args[value.name]; - } - } - } - - req = new window.SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this); - if (opts.mock != null) { - return req; - } else { - return true; - } - }; - - SwaggerOperation.prototype.pathJson = function() { - return this.path.replace("{format}", "json"); - }; - - SwaggerOperation.prototype.pathXml = function() { - return this.path.replace("{format}", "xml"); - }; - - SwaggerOperation.prototype.urlify = function(args) { - var param, queryParams, reg, url, _i, _j, _len, _len1, _ref, _ref1; - url = this.resource.basePath + this.pathJson(); - _ref = this.parameters; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - param = _ref[_i]; - if (param.paramType === 'path') { - if (args[param.name]) { - reg = new RegExp('\{' + param.name + '[^\}]*\}', 'gi'); - url = url.replace(reg, encodeURIComponent(args[param.name])); - delete args[param.name]; - } else { - throw "" + param.name + " is a required path param."; - } - } - } - queryParams = ""; - _ref1 = this.parameters; - for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { - param = _ref1[_j]; - if (param.paramType === 'query') { - if (args[param.name]) { - if (queryParams !== "") { - queryParams += "&"; - } - queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]); - } - } - } - if ((queryParams != null) && queryParams.length > 0) { - url += "?" + queryParams; - } - return url; - }; - - SwaggerOperation.prototype.supportHeaderParams = function() { - return this.resource.api.supportHeaderParams; - }; - - SwaggerOperation.prototype.supportedSubmitMethods = function() { - return this.resource.api.supportedSubmitMethods; - }; - - SwaggerOperation.prototype.getQueryParams = function(args) { - return this.getMatchingParams(['query'], args); - }; - - SwaggerOperation.prototype.getHeaderParams = function(args) { - return this.getMatchingParams(['header'], args); - }; - - SwaggerOperation.prototype.getMatchingParams = function(paramTypes, args) { - var matchingParams, name, param, value, _i, _len, _ref, _ref1; - matchingParams = {}; - _ref = this.parameters; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - param = _ref[_i]; - if (args && args[param.name]) { - matchingParams[param.name] = args[param.name]; - } - } - _ref1 = this.resource.api.headers; - for (name in _ref1) { - value = _ref1[name]; - matchingParams[name] = value; - } - return matchingParams; - }; - - SwaggerOperation.prototype.help = function() { - var msg, parameter, _i, _len, _ref; - msg = ""; - _ref = this.parameters; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - parameter = _ref[_i]; - if (msg !== "") { - msg += "\n"; - } - msg += "* " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description; - } - return msg; - }; - - return SwaggerOperation; - - })(); - this.SwaggerApi = SwaggerApi; this.SwaggerResource = SwaggerResource; - this.SwaggerOperation = SwaggerOperation; this.SwaggerModelProperty = SwaggerModelProperty; this.PasswordAuthorization = PasswordAuthorization; }).call(this); From 3585286e76418606c55d70e594af07fdcd6c821c Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 11 Feb 2014 07:42:11 -0800 Subject: [PATCH 03/13] more clean-up --- lib/swagger.js | 1487 +++++++++++++++++++++++------------------------- 1 file changed, 711 insertions(+), 776 deletions(-) diff --git a/lib/swagger.js b/lib/swagger.js index 1f77c69d9..d56444cfd 100644 --- a/lib/swagger.js +++ b/lib/swagger.js @@ -4,6 +4,616 @@ var __bind = function(fn, me){ }; }; +log = function() { + if (window.console) + return console.log.apply(console, arguments); +}; + +var SwaggerApi = function(url, options) { + if (options == null) { + options = {}; + } + if (url) { + if (url.url) { + options = url; + } else { + this.url = url; + } + } else { + options = url; + } + if (options.url != null) { + this.url = options.url; + } + if (options.success != null) { + this.success = options.success; + } + this.failure = options.failure != null ? options.failure : function() {}; + this.progress = options.progress != null ? options.progress : function() {}; + if (options.success != null) { + this.build(); + } +} + +SwaggerApi.prototype.url = "http://api.wordnik.com/v4/resources.json"; + +SwaggerApi.prototype.debug = false; + +SwaggerApi.prototype.basePath = null; + +SwaggerApi.prototype.authorizations = null; + +SwaggerApi.prototype.authorizationScheme = null; + +SwaggerApi.prototype.info = null; + +SwaggerApi.prototype.useJQuery = null; + + +SwaggerApi.prototype.build = function() { + var e, obj, + _this = this; + this.progress('fetching resource list: ' + this.url); + obj = { + useJQuery: this.useJQuery, + url: this.url, + method: "get", + headers: { + accept: "application/json" + }, + on: { + error: function(response) { + if (_this.url.substring(0, 4) !== 'http') { + return _this.fail('Please specify the protocol for ' + _this.url); + } else if (response.status === 0) { + return _this.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.'); + } else if (response.status === 404) { + return _this.fail('Can\'t read swagger JSON from ' + _this.url); + } else { + return _this.fail(response.status + ' : ' + response.statusText + ' ' + _this.url); + } + }, + response: function(response) { + var responseObj; + responseObj = JSON.parse(response.data); + _this.swaggerVersion = responseObj.swaggerVersion; + if (_this.swaggerVersion === "1.2") { + return _this.buildFromSpec(responseObj); + } else { + return _this.buildFrom1_1Spec(responseObj); + } + } + } + }; + e = {}; + if (typeof window !== 'undefined') { + e = window; + } else { + e = exports; + } + e.authorizations.apply(obj); + new SwaggerHttp().execute(obj); + return this; +}; + +SwaggerApi.prototype.buildFromSpec = function(response) { + var api, isApi, newName, operation, res, resource, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2; + if (response.apiVersion != null) { + this.apiVersion = response.apiVersion; + } + this.apis = {}; + this.apisArray = []; + this.produces = response.produces; + this.authSchemes = response.authorizations; + if (response.info != null) { + this.info = response.info; + } + isApi = false; + _ref = response.apis; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + api = _ref[_i]; + if (api.operations) { + _ref1 = api.operations; + for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { + operation = _ref1[_j]; + isApi = true; + } + } + } + if (response.basePath) { + this.basePath = response.basePath; + } else if (this.url.indexOf('?') > 0) { + this.basePath = this.url.substring(0, this.url.lastIndexOf('?')); + } else { + this.basePath = this.url; + } + if (isApi) { + newName = response.resourcePath.replace(/\//g, ''); + this.resourcePath = response.resourcePath; + res = new SwaggerResource(response, this); + this.apis[newName] = res; + this.apisArray.push(res); + } else { + _ref2 = response.apis; + for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { + resource = _ref2[_k]; + res = new SwaggerResource(resource, this); + this.apis[res.name] = res; + this.apisArray.push(res); + } + } + if (this.success) { + this.success(); + } + return this; +}; + +SwaggerApi.prototype.buildFrom1_1Spec = function(response) { + var api, isApi, newName, operation, res, resource, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2; + 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 = {}; + this.apisArray = []; + this.produces = response.produces; + if (response.info != null) { + this.info = response.info; + } + isApi = false; + _ref = response.apis; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + api = _ref[_i]; + if (api.operations) { + _ref1 = api.operations; + for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { + operation = _ref1[_j]; + isApi = true; + } + } + } + if (response.basePath) { + this.basePath = response.basePath; + } else if (this.url.indexOf('?') > 0) { + this.basePath = this.url.substring(0, this.url.lastIndexOf('?')); + } else { + this.basePath = this.url; + } + if (isApi) { + newName = response.resourcePath.replace(/\//g, ''); + this.resourcePath = response.resourcePath; + res = new SwaggerResource(response, this); + this.apis[newName] = res; + this.apisArray.push(res); + } else { + _ref2 = response.apis; + for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { + resource = _ref2[_k]; + res = new SwaggerResource(resource, this); + this.apis[res.name] = res; + this.apisArray.push(res); + } + } + if (this.success) { + this.success(); + } + return this; +}; + +SwaggerApi.prototype.selfReflect = function() { + var resource, resource_name, _ref; + if (this.apis == null) { + return false; + } + _ref = this.apis; + for (resource_name in _ref) { + resource = _ref[resource_name]; + if (resource.ready == null) { + return false; + } + } + this.setConsolidatedModels(); + this.ready = true; + if (this.success != null) { + return this.success(); + } +}; + +SwaggerApi.prototype.fail = function(message) { + this.failure(message); + throw message; +}; + +SwaggerApi.prototype.setConsolidatedModels = function() { + var model, modelName, resource, resource_name, _i, _len, _ref, _ref1, _results; + this.modelsArray = []; + this.models = {}; + _ref = this.apis; + for (resource_name in _ref) { + resource = _ref[resource_name]; + for (modelName in resource.models) { + if (this.models[modelName] == null) { + this.models[modelName] = resource.models[modelName]; + this.modelsArray.push(resource.models[modelName]); + } + } + } + _ref1 = this.modelsArray; + _results = []; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + model = _ref1[_i]; + _results.push(model.setReferencedModels(this.models)); + } + return _results; +}; + +SwaggerApi.prototype.help = function() { + var operation, operation_name, parameter, resource, resource_name, _i, _len, _ref, _ref1, _ref2; + _ref = this.apis; + for (resource_name in _ref) { + resource = _ref[resource_name]; + log(resource_name); + _ref1 = resource.operations; + for (operation_name in _ref1) { + operation = _ref1[operation_name]; + 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); + } + } + } + return this; +}; + +var SwaggerResource = function(resourceObj, api) { + var _this = this; + this.api = api; + this.api = this.api; + produces = []; + consumes = []; + this.path = this.api.resourcePath != null ? this.api.resourcePath : resourceObj.path; + this.description = resourceObj.description; + + var parts = this.path.split("/"); + this.name = parts[parts.length - 1].replace('.{format}', ''); + this.basePath = this.api.basePath; + this.operations = {}; + this.operationsArray = []; + this.modelsArray = []; + this.models = {}; + this.rawModels = {}; + + if ((resourceObj.apis != null) && (this.api.resourcePath != null)) { + this.addApiDeclaration(resourceObj); + } else { + if (this.path == null) { + this.api.fail("SwaggerResources must have a path."); + } + if (this.path.substring(0, 4) === 'http') { + this.url = this.path.replace('{format}', 'json'); + } else { + this.url = this.api.basePath + this.path.replace('{format}', 'json'); + } + this.api.progress('fetching resource ' + this.name + ': ' + this.url); + obj = { + url: this.url, + method: "get", + useJQuery: this.useJQuery, + headers: { + accept: "application/json" + }, + on: { + error: function(response) { + return _this.api.fail("Unable to read api '" + _this.name + "' from path " + _this.url + " (server returned " + response.statusText + ")"); + }, + response: function(response) { + var responseObj; + responseObj = JSON.parse(response.data); + return _this.addApiDeclaration(responseObj); + } + } + }; + e = {}; + if (typeof window !== 'undefined') { + e = window; + } else { + e = exports; + } + e.authorizations.apply(obj); + new SwaggerHttp().execute(obj); + } +} + +SwaggerResource.prototype.api = null; +SwaggerResource.prototype.produces = null; +SwaggerResource.prototype.consumes = null; + +SwaggerResource.prototype.getAbsoluteBasePath = function(relativeBasePath) { + var parts, pos, url; + url = this.api.basePath; + pos = url.lastIndexOf(relativeBasePath); + if (pos === -1) { + parts = url.split("/"); + url = parts[0] + "//" + parts[2]; + if (relativeBasePath.indexOf("/") === 0) { + return url + relativeBasePath; + } else { + return url + "/" + relativeBasePath; + } + } else if (relativeBasePath === "/") { + return url.substring(0, pos); + } else { + return url.substring(0, pos) + relativeBasePath; + } +}; + +SwaggerResource.prototype.addApiDeclaration = function(response) { + if (response.produces != null) + this.produces = response.produces; + 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.addModels(response.models); + if (response.apis) { + for (var i = 0 ; i < response.apis.length; i++) { + var endpoint = response.apis[i]; + this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces); + } + } + this.api[this.name] = this; + this.ready = true; + return this.api.selfReflect(); +}; + +SwaggerResource.prototype.addModels = function(models) { + if (models != null) { + for (modelName in models) { + if (this.models[modelName] == null) { + var swaggerModel = new SwaggerModel(modelName, models[modelName]); + this.modelsArray.push(swaggerModel); + this.models[modelName] = swaggerModel; + this.rawModels[modelName] = models[modelName]; + } + } + var output = []; + for (var i = 0; i < this.modelsArray; i++) { + model = this.modelsArray[_i]; + output.push(model.setReferencedModels(this.models)); + } + return output; + } +}; + +SwaggerResource.prototype.addOperations = function(resource_path, ops, consumes, produces) { + if (ops) { + output = []; + for (var i = 0; i < ops.length; i++) { + o = ops[i]; + consumes = this.consumes; + produces = this.produces; + if (o.consumes != null) + consumes = o.consumes; + else + consumes = this.consumes; + + if (o.produces != null) + produces = o.produces; + else + produces = this.produces; + type = (o.type||o.responseClass); + + if (type === "array") { + ref = null; + if (o.items) + ref = o.items["type"] || o.items["$ref"]; + type = "array[" + ref + "]"; + } + responseMessages = o.responseMessages; + method = o.method; + if (o.httpMethod) { + method = o.httpMethod; + } + if (o.supportedContentTypes) { + consumes = o.supportedContentTypes; + } + if (o.errorResponses) { + responseMessages = o.errorResponses; + for (j = 0; j < responseMessages.length; j++) { + r = responseMessages[j]; + r.message = r.reason; + r.reason = null; + } + } + o.nickname = this.sanitize(o.nickname); + op = new SwaggerOperation(o.nickname, resource_path, method, o.parameters, o.summary, o.notes, type, responseMessages, this, consumes, produces, o.authorizations); + this.operations[op.nickname] = op; + output.push(this.operationsArray.push(op)); + } + return output; + } +}; + +SwaggerResource.prototype.sanitize = function(nickname) { + var op; + op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|./?,\\'""-]/g, '_'); + op = op.replace(/((_){2,})/g, '_'); + op = op.replace(/^(_)*/g, ''); + op = op.replace(/([_])*$/g, ''); + return op; +}; + +SwaggerResource.prototype.help = function() { + var msg, operation, operation_name, parameter, _i, _len, _ref, _ref1, _results; + _ref = this.operations; + _results = []; + for (operation_name in _ref) { + operation = _ref[operation_name]; + msg = " " + operation.nickname; + _ref1 = operation.parameters; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + parameter = _ref1[_i]; + msg.concat(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description); + } + _results.push(msg); + } + return _results; +}; + +var SwaggerModel = function(modelName, obj) { + this.name = obj.id != null ? obj.id : modelName; + this.properties = []; + for (propertyName in obj.properties) { + if (obj.required != null) { + for (value in obj.required) { + if (propertyName === obj.required[value]) { + obj.properties[propertyName].required = true; + } + } + } + prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName]); + this.properties.push(prop); + } +} + +SwaggerModel.prototype.setReferencedModels = function(allModels) { + var results = []; + for (i = 0; i < this.properties.length; i++) { + var property = this.properties[i]; + var type = property.type || property.dataType; + if (allModels[type] != null) + results.push(property.refModel = allModels[type]); + else if ((property.refDataType != null) && (allModels[property.refDataType] != null)) + results.push(property.refModel = allModels[property.refDataType]); + else + results.push(void 0); + } + return results; +}; + +SwaggerModel.prototype.getMockSignature = function(modelsToIgnore) { + var propertiesStr = []; + for (i = 0; i < this.properties.length; i++) { + prop = this.properties[i]; + propertiesStr.push(prop.toString()); + } + + var strong = ''; + var stronger = ''; + var strongClose = ''; + var classOpen = strong + this.name + ' {' + strongClose; + var classClose = strong + '}' + strongClose; + var returnVal = classOpen + '
' + propertiesStr.join(',
') + '
' + classClose; + if (!modelsToIgnore) + modelsToIgnore = []; + modelsToIgnore.push(this); + + for (i = 0; i < this.properties.length; i++) { + prop = this.properties[i]; + if ((prop.refModel != null) && modelsToIgnore.indexOf(prop.refModel) === -1) { + returnVal = returnVal + ('
' + prop.refModel.getMockSignature(modelsToIgnore)); + } + } + return returnVal; +}; + +SwaggerModel.prototype.createJSONSample = function(modelsToIgnore) { + var result = {}; + var modelsToIgnore = (modelsToIgnore||[]) + modelsToIgnore.push(this.name); + for (i = 0; i < this.properties.length; i++) { + prop = this.properties[i]; + result[prop.name] = prop.getSampleValue(modelsToIgnore); + } + modelsToIgnore.pop(this.name); + return result; +}; + +var SwaggerModelProperty = function(name, obj) { + this.name = name; + 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; + if (obj.items != null) { + if (obj.items.type != null) { + this.refDataType = obj.items.type; + } + if (obj.items.$ref != null) { + this.refDataType = obj.items.$ref; + } + } + this.dataTypeWithRef = this.refDataType != null ? (this.dataType + '[' + this.refDataType + ']') : this.dataType; + if (obj.allowableValues != null) { + this.valueType = obj.allowableValues.valueType; + this.values = obj.allowableValues.values; + if (this.values != null) { + this.valuesString = "'" + this.values.join("' or '") + "'"; + } + } + if (obj["enum"] != null) { + this.valueType = "string"; + this.values = obj["enum"]; + if (this.values != null) { + this.valueString = "'" + this.values.join("' or '") + "'"; + } + } +} + +SwaggerModelProperty.prototype.getSampleValue = function(modelsToIgnore) { + var result; + if ((this.refModel != null) && (modelsToIgnore[this.refModel.name] === 'undefined')) { + result = this.refModel.createJSONSample(modelsToIgnore); + } else { + if (this.isCollection) { + result = this.toSampleValue(this.refDataType); + } else { + result = this.toSampleValue(this.dataType); + } + } + if (this.isCollection) { + return [result]; + } else { + return result; + } +}; + +SwaggerModelProperty.prototype.toSampleValue = function(value) { + var result; + if (value === "integer") { + result = 0; + } else if (value === "boolean") { + result = false; + } else if (value === "double") { + result = 0.0; + } else if (value === "string") { + result = ""; + } else { + result = value; + } + return result; +}; + +SwaggerModelProperty.prototype.toString = function() { + var req, str; + req = this.required ? 'propReq' : 'propOpt'; + str = '' + this.name + ' (' + this.dataTypeWithRef + ''; + if (!this.required) { + str += ', optional'; + } + str += ')'; + if (this.values != null) { + str += " = ['" + this.values.join("' or '") + "']"; + } + if (this.descr != null) { + str += ': ' + this.descr + ''; + } + return str; +}; + var SwaggerOperation = function(nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations) { var parameter, v, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _ref3, _this = this; @@ -38,56 +648,61 @@ var SwaggerOperation = function(nickname, path, method, parameters, summary, not this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models); } - _ref1 = this.parameters; - for (_i = 0, _len = _ref1.length; _i < _len; _i++) { - parameter = _ref1[_i]; - parameter.name = parameter.name || parameter.type || parameter.dataType; - type = parameter.type || parameter.dataType; - if (type.toLowerCase() === 'boolean') { - parameter.allowableValues = {}; - parameter.allowableValues.values = ["true", "false"]; + for(i = 0; i < parameters.length; i ++) { + var param = parameters[i]; + // might take this away + param.name = param.name || param.type || param.dataType; + + // for 1.1 compatibility + var type = param.type || param.dataType; + + if(type.toLowerCase() === 'boolean') { + param.allowableValues = {}; + param.allowableValues.values = ["true", "false"]; } - parameter.signature = this.getSignature(type, this.resource.models); - parameter.sampleJSON = this.getSampleJSON(type, this.resource.models); - if (parameter["enum"] != null) { - parameter.isList = true; - parameter.allowableValues = {}; - parameter.allowableValues.descriptiveValues = []; - _ref2 = parameter["enum"]; - for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { - v = _ref2[_j]; - if ((parameter.defaultValue != null) && parameter.defaultValue === v) { - parameter.allowableValues.descriptiveValues.push({ + param.signature = this.getSignature(type, this.resource.models); + param.sampleJSON = this.getSampleJSON(type, this.resource.models); + + var enumValue = param["enum"]; + if(enumValue != null) { + param.isList = true; + param.allowableValues = {}; + param.allowableValues.descriptiveValues = []; + + for(j = 0; j < enumValue.length; j++) { + var v = enumValue[j]; + if(param.defaultValue != null) { + param.allowableValues.descriptiveValues.push ({ value: String(v), - isDefault: true + isDefault: (v === param.defaultValue) }); - } else { - parameter.allowableValues.descriptiveValues.push({ + } + else { + param.allowableValues.descriptiveValues.push ({ value: String(v), isDefault: false }); } } } - if (parameter.allowableValues != null) { - if (parameter.allowableValues.valueType === "RANGE") { - parameter.isRange = true; - } else { - parameter.isList = true; - } - if (parameter.allowableValues.values != null) { - parameter.allowableValues.descriptiveValues = []; - _ref3 = parameter.allowableValues.values; - for (_k = 0, _len2 = _ref3.length; _k < _len2; _k++) { - v = _ref3[_k]; - if ((parameter.defaultValue != null) && parameter.defaultValue === v) { - parameter.allowableValues.descriptiveValues.push({ - value: v, - isDefault: true + if(param.allowableValues != null) { + if(param.allowableValues.valueType === "RANGE") + param.isRange = true; + else + param.isList = true; + if(param.allowableValues != null) { + param.allowableValues.descriptiveValues = []; + for(j = 0; j < param.allowableValues.values; j++){ + var v = param.allowableValues.values[j]; + if(param.defaultValue != null) { + param.allowableValues.descriptiveValues.push ({ + value: String(v), + isDefault: (v === param.defaultValue) }); - } else { - parameter.allowableValues.descriptiveValues.push({ - value: v, + } + else { + param.allowableValues.descriptiveValues.push ({ + value: String(v), isDefault: false }); } @@ -179,31 +794,23 @@ SwaggerOperation.prototype["do"] = function(args, opts, callback, error) { params.headers = args.headers; delete args.headers; } - _ref = this.parameters; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - param = _ref[_i]; - if (param.paramType === "header") { - if (args[param.name]) { + + var possibleParams = []; + for(i = 0; i < this.parameters.length; i++) { + var param = this.parameters[i]; + if(param.paramType === 'header') { + if(args[param.name]) params.headers[param.name] = args[param.name]; - } } + else if(param.paramType === 'form' || param.paramType.toLowerCase() === 'file') + possibleParams.push(param); } + if (args.body != null) { params.body = args.body; delete args.body; } - possibleParams = (function() { - var _j, _len1, _ref1, _results; - _ref1 = this.parameters; - _results = []; - for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { - param = _ref1[_j]; - if (param.paramType === "form" || param.paramType.toLowerCase() === "file") { - _results.push(param); - } - } - return _results; - }).call(this); + if (possibleParams) { for (key in possibleParams) { value = possibleParams[key]; @@ -213,7 +820,7 @@ SwaggerOperation.prototype["do"] = function(args, opts, callback, error) { } } - req = new window.SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this); + req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this); if (opts.mock != null) { return req; } else { @@ -230,37 +837,33 @@ SwaggerOperation.prototype.pathXml = function() { }; SwaggerOperation.prototype.urlify = function(args) { - var param, queryParams, reg, url, _i, _j, _len, _len1, _ref, _ref1; - url = this.resource.basePath + this.pathJson(); - _ref = this.parameters; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - param = _ref[_i]; + var url = this.resource.basePath + this.pathJson(); + var params = this.parameters; + for(i = 0; i < params.length; i ++){ + var param = params[i]; if (param.paramType === 'path') { - if (args[param.name]) { - reg = new RegExp('\{' + param.name + '[^\}]*\}', 'gi'); + if(args[param.name]) { + // apply path params and remove from args + var reg = new RegExp('\{' + param.name + '[^\}]*\}', 'gi'); url = url.replace(reg, encodeURIComponent(args[param.name])); delete args[param.name]; - } else { - throw "" + param.name + " is a required path param."; } + else + throw "" + param.name + " is a required path param."; } } - queryParams = ""; - _ref1 = this.parameters; - for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { - param = _ref1[_j]; - if (param.paramType === 'query') { - if (args[param.name]) { - if (queryParams !== "") { - queryParams += "&"; - } - queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]); - } + + var queryParams = ""; + for(i = 0; i < params.length; i ++){ + var param = params[i]; + if(param.paramType === 'query') { + if(queryParams !== '') + queryParams += "&"; + queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]); } } - if ((queryParams != null) && queryParams.length > 0) { - url += "?" + queryParams; - } + if ((queryParams != null) && queryParams.length > 0) + url += '?' + queryParams; return url; }; @@ -281,33 +884,29 @@ SwaggerOperation.prototype.getHeaderParams = function(args) { }; SwaggerOperation.prototype.getMatchingParams = function(paramTypes, args) { - var matchingParams, name, param, value, _i, _len, _ref, _ref1; - matchingParams = {}; - _ref = this.parameters; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - param = _ref[_i]; - if (args && args[param.name]) { + var matchingParams = {}; + var params = this.parameters; + for (i = 0; i < params.length; i++) { + param = params[i]; + if (args && args[param.name]) matchingParams[param.name] = args[param.name]; - } } - _ref1 = this.resource.api.headers; - for (name in _ref1) { - value = _ref1[name]; + var headers = this.resource.api.headers; + for (name in headers) { + var value = headers[name]; matchingParams[name] = value; } return matchingParams; }; SwaggerOperation.prototype.help = function() { - var msg, parameter, _i, _len, _ref; - msg = ""; - _ref = this.parameters; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - parameter = _ref[_i]; - if (msg !== "") { + var msg = ""; + var params = this.parameters; + for (i = 0; i < params.length; i++) { + var param = params[i]; + if (msg !== "") msg += "\n"; - } - msg += "* " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description; + msg += "* " + param.name + (param.required ? ' (required)' : '') + " - " + param.description; } return msg; }; @@ -703,8 +1302,6 @@ var PasswordAuthorization = function(name, username, password) { this.password = password; this._btoa = null; - this.foo = function() {}; - if (typeof window !== 'undefined') return this._btoa = btoa; else @@ -716,677 +1313,15 @@ PasswordAuthorization.prototype.apply = function(obj, authorizations) { return true; }; -if(typeof exports !== 'undefined') { - exports.SwaggerAuthorizations = SwaggerAuthorizations; - exports.SwaggerHttp = SwaggerHttp; - exports.JQueryHttpClient = JQueryHttpClient; - exports.ShredHttpClient = ShredHttpClient; - exports.PasswordAuthorization = PasswordAuthorization; -} -else if (typeof window != 'undefined') { - this.SwaggerHttp = SwaggerHttp; - this.SwaggerRequest = SwaggerRequest; - this.authorizations = new SwaggerAuthorizations(); - this.JQueryHttpClient = JQueryHttpClient; - this.ShredHttpClient = ShredHttpClient; - this.SwaggerOperation = SwaggerOperation; -}; - - -(function() { - var SwaggerApi, SwaggerAuthorizations, SwaggerModel, SwaggerModelProperty, SwaggerOperation, SwaggerRequest, SwaggerResource, log, - __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, - __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; - - log = function() { - if (window.console) { - return console.log.apply(console, arguments); - } - }; - - SwaggerApi = (function() { - SwaggerApi.prototype.url = "http://api.wordnik.com/v4/resources.json"; - - SwaggerApi.prototype.debug = false; - - SwaggerApi.prototype.basePath = null; - - SwaggerApi.prototype.authorizations = null; - - SwaggerApi.prototype.authorizationScheme = null; - - SwaggerApi.prototype.info = null; - - SwaggerApi.prototype.useJQuery = null; - - function SwaggerApi(url, options) { - if (options == null) { - options = {}; - } - if (url) { - if (url.url) { - options = url; - } else { - this.url = url; - } - } else { - options = url; - } - if (options.url != null) { - this.url = options.url; - } - if (options.success != null) { - this.success = options.success; - } - this.failure = options.failure != null ? options.failure : function() {}; - this.progress = options.progress != null ? options.progress : function() {}; - if (options.success != null) { - this.build(); - } - } - - SwaggerApi.prototype.build = function() { - var e, obj, - _this = this; - this.progress('fetching resource list: ' + this.url); - obj = { - useJQuery: this.useJQuery, - url: this.url, - method: "get", - headers: { - accept: "application/json" - }, - on: { - error: function(response) { - if (_this.url.substring(0, 4) !== 'http') { - return _this.fail('Please specify the protocol for ' + _this.url); - } else if (response.status === 0) { - return _this.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.'); - } else if (response.status === 404) { - return _this.fail('Can\'t read swagger JSON from ' + _this.url); - } else { - return _this.fail(response.status + ' : ' + response.statusText + ' ' + _this.url); - } - }, - response: function(response) { - var responseObj; - responseObj = JSON.parse(response.data); - _this.swaggerVersion = responseObj.swaggerVersion; - if (_this.swaggerVersion === "1.2") { - return _this.buildFromSpec(responseObj); - } else { - return _this.buildFrom1_1Spec(responseObj); - } - } - } - }; - e = {}; - if (typeof window !== 'undefined') { - e = window; - } else { - e = exports; - } - e.authorizations.apply(obj); - new SwaggerHttp().execute(obj); - return this; - }; - - SwaggerApi.prototype.buildFromSpec = function(response) { - var api, isApi, newName, operation, res, resource, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2; - if (response.apiVersion != null) { - this.apiVersion = response.apiVersion; - } - this.apis = {}; - this.apisArray = []; - this.produces = response.produces; - this.authSchemes = response.authorizations; - if (response.info != null) { - this.info = response.info; - } - isApi = false; - _ref = response.apis; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - api = _ref[_i]; - if (api.operations) { - _ref1 = api.operations; - for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { - operation = _ref1[_j]; - isApi = true; - } - } - } - if (response.basePath) { - this.basePath = response.basePath; - } else if (this.url.indexOf('?') > 0) { - this.basePath = this.url.substring(0, this.url.lastIndexOf('?')); - } else { - this.basePath = this.url; - } - if (isApi) { - newName = response.resourcePath.replace(/\//g, ''); - this.resourcePath = response.resourcePath; - res = new SwaggerResource(response, this); - this.apis[newName] = res; - this.apisArray.push(res); - } else { - _ref2 = response.apis; - for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { - resource = _ref2[_k]; - res = new SwaggerResource(resource, this); - this.apis[res.name] = res; - this.apisArray.push(res); - } - } - if (this.success) { - this.success(); - } - return this; - }; - - SwaggerApi.prototype.buildFrom1_1Spec = function(response) { - var api, isApi, newName, operation, res, resource, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2; - 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 = {}; - this.apisArray = []; - this.produces = response.produces; - if (response.info != null) { - this.info = response.info; - } - isApi = false; - _ref = response.apis; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - api = _ref[_i]; - if (api.operations) { - _ref1 = api.operations; - for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { - operation = _ref1[_j]; - isApi = true; - } - } - } - if (response.basePath) { - this.basePath = response.basePath; - } else if (this.url.indexOf('?') > 0) { - this.basePath = this.url.substring(0, this.url.lastIndexOf('?')); - } else { - this.basePath = this.url; - } - if (isApi) { - newName = response.resourcePath.replace(/\//g, ''); - this.resourcePath = response.resourcePath; - res = new SwaggerResource(response, this); - this.apis[newName] = res; - this.apisArray.push(res); - } else { - _ref2 = response.apis; - for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { - resource = _ref2[_k]; - res = new SwaggerResource(resource, this); - this.apis[res.name] = res; - this.apisArray.push(res); - } - } - if (this.success) { - this.success(); - } - return this; - }; - - SwaggerApi.prototype.selfReflect = function() { - var resource, resource_name, _ref; - if (this.apis == null) { - return false; - } - _ref = this.apis; - for (resource_name in _ref) { - resource = _ref[resource_name]; - if (resource.ready == null) { - return false; - } - } - this.setConsolidatedModels(); - this.ready = true; - if (this.success != null) { - return this.success(); - } - }; - - SwaggerApi.prototype.fail = function(message) { - this.failure(message); - throw message; - }; - - SwaggerApi.prototype.setConsolidatedModels = function() { - var model, modelName, resource, resource_name, _i, _len, _ref, _ref1, _results; - this.modelsArray = []; - this.models = {}; - _ref = this.apis; - for (resource_name in _ref) { - resource = _ref[resource_name]; - for (modelName in resource.models) { - if (this.models[modelName] == null) { - this.models[modelName] = resource.models[modelName]; - this.modelsArray.push(resource.models[modelName]); - } - } - } - _ref1 = this.modelsArray; - _results = []; - for (_i = 0, _len = _ref1.length; _i < _len; _i++) { - model = _ref1[_i]; - _results.push(model.setReferencedModels(this.models)); - } - return _results; - }; - - SwaggerApi.prototype.help = function() { - var operation, operation_name, parameter, resource, resource_name, _i, _len, _ref, _ref1, _ref2; - _ref = this.apis; - for (resource_name in _ref) { - resource = _ref[resource_name]; - log(resource_name); - _ref1 = resource.operations; - for (operation_name in _ref1) { - operation = _ref1[operation_name]; - 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); - } - } - } - return this; - }; - - return SwaggerApi; - - })(); - - SwaggerResource = (function() { - SwaggerResource.prototype.api = null; - - SwaggerResource.prototype.produces = null; - - SwaggerResource.prototype.consumes = null; - - function SwaggerResource(resourceObj, api) { - var consumes, e, obj, parts, produces, - _this = this; - this.api = api; - this.api = this.api; - produces = []; - consumes = []; - this.path = this.api.resourcePath != null ? this.api.resourcePath : resourceObj.path; - this.description = resourceObj.description; - parts = this.path.split("/"); - this.name = parts[parts.length - 1].replace('.{format}', ''); - this.basePath = this.api.basePath; - this.operations = {}; - this.operationsArray = []; - this.modelsArray = []; - this.models = {}; - this.rawModels = {}; - if ((resourceObj.apis != null) && (this.api.resourcePath != null)) { - this.addApiDeclaration(resourceObj); - } else { - if (this.path == null) { - this.api.fail("SwaggerResources must have a path."); - } - if (this.path.substring(0, 4) === 'http') { - this.url = this.path.replace('{format}', 'json'); - } else { - this.url = this.api.basePath + this.path.replace('{format}', 'json'); - } - this.api.progress('fetching resource ' + this.name + ': ' + this.url); - obj = { - url: this.url, - method: "get", - useJQuery: this.useJQuery, - headers: { - accept: "application/json" - }, - on: { - error: function(response) { - return _this.api.fail("Unable to read api '" + _this.name + "' from path " + _this.url + " (server returned " + response.statusText + ")"); - }, - response: function(response) { - var responseObj; - responseObj = JSON.parse(response.data); - return _this.addApiDeclaration(responseObj); - } - } - }; - e = {}; - if (typeof window !== 'undefined') { - e = window; - } else { - e = exports; - } - e.authorizations.apply(obj); - new SwaggerHttp().execute(obj); - } - } - - SwaggerResource.prototype.getAbsoluteBasePath = function(relativeBasePath) { - var parts, pos, url; - url = this.api.basePath; - pos = url.lastIndexOf(relativeBasePath); - if (pos === -1) { - parts = url.split("/"); - url = parts[0] + "//" + parts[2]; - if (relativeBasePath.indexOf("/") === 0) { - return url + relativeBasePath; - } else { - return url + "/" + relativeBasePath; - } - } else if (relativeBasePath === "/") { - return url.substring(0, pos); - } else { - return url.substring(0, pos) + relativeBasePath; - } - }; - - SwaggerResource.prototype.addApiDeclaration = function(response) { - var endpoint, _i, _len, _ref; - if (response.produces != null) { - this.produces = response.produces; - } - 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.addModels(response.models); - if (response.apis) { - _ref = response.apis; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - endpoint = _ref[_i]; - this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces); - } - } - this.api[this.name] = this; - this.ready = true; - return this.api.selfReflect(); - }; - - SwaggerResource.prototype.addModels = function(models) { - var model, modelName, swaggerModel, _i, _len, _ref, _results; - if (models != null) { - for (modelName in models) { - if (this.models[modelName] == null) { - swaggerModel = new SwaggerModel(modelName, models[modelName]); - this.modelsArray.push(swaggerModel); - this.models[modelName] = swaggerModel; - this.rawModels[modelName] = models[modelName]; - } - } - _ref = this.modelsArray; - _results = []; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - model = _ref[_i]; - _results.push(model.setReferencedModels(this.models)); - } - return _results; - } - }; - - SwaggerResource.prototype.addOperations = function(resource_path, ops, consumes, produces) { - var method, o, op, r, ref, responseMessages, type, _i, _j, _len, _len1, _results; - if (ops) { - _results = []; - for (_i = 0, _len = ops.length; _i < _len; _i++) { - o = ops[_i]; - consumes = this.consumes; - produces = this.produces; - if (o.consumes != null) { - consumes = o.consumes; - } else { - consumes = this.consumes; - } - if (o.produces != null) { - produces = o.produces; - } else { - produces = this.produces; - } - type = o.type || o.responseClass; - if (type === "array") { - ref = null; - if (o.items) { - ref = o.items["type"] || o.items["$ref"]; - } - type = "array[" + ref + "]"; - } - responseMessages = o.responseMessages; - method = o.method; - if (o.httpMethod) { - method = o.httpMethod; - } - if (o.supportedContentTypes) { - consumes = o.supportedContentTypes; - } - if (o.errorResponses) { - responseMessages = o.errorResponses; - for (_j = 0, _len1 = responseMessages.length; _j < _len1; _j++) { - r = responseMessages[_j]; - r.message = r.reason; - r.reason = null; - } - } - o.nickname = this.sanitize(o.nickname); - op = new window.SwaggerOperation(o.nickname, resource_path, method, o.parameters, o.summary, o.notes, type, responseMessages, this, consumes, produces, o.authorizations); - this.operations[op.nickname] = op; - _results.push(this.operationsArray.push(op)); - } - return _results; - } - }; - - SwaggerResource.prototype.sanitize = function(nickname) { - var op; - op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|./?,\\'""-]/g, '_'); - op = op.replace(/((_){2,})/g, '_'); - op = op.replace(/^(_)*/g, ''); - op = op.replace(/([_])*$/g, ''); - return op; - }; - - SwaggerResource.prototype.help = function() { - var msg, operation, operation_name, parameter, _i, _len, _ref, _ref1, _results; - _ref = this.operations; - _results = []; - for (operation_name in _ref) { - operation = _ref[operation_name]; - msg = " " + operation.nickname; - _ref1 = operation.parameters; - for (_i = 0, _len = _ref1.length; _i < _len; _i++) { - parameter = _ref1[_i]; - msg.concat(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description); - } - _results.push(msg); - } - return _results; - }; - - return SwaggerResource; - - })(); - - SwaggerModel = (function() { - function SwaggerModel(modelName, obj) { - var prop, propertyName, value; - this.name = obj.id != null ? obj.id : modelName; - this.properties = []; - for (propertyName in obj.properties) { - if (obj.required != null) { - for (value in obj.required) { - if (propertyName === obj.required[value]) { - obj.properties[propertyName].required = true; - } - } - } - prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName]); - this.properties.push(prop); - } - } - - SwaggerModel.prototype.setReferencedModels = function(allModels) { - var prop, type, _i, _len, _ref, _results; - _ref = this.properties; - _results = []; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - prop = _ref[_i]; - type = prop.type || prop.dataType; - if (allModels[type] != null) { - _results.push(prop.refModel = allModels[type]); - } else if ((prop.refDataType != null) && (allModels[prop.refDataType] != null)) { - _results.push(prop.refModel = allModels[prop.refDataType]); - } else { - _results.push(void 0); - } - } - return _results; - }; - - SwaggerModel.prototype.getMockSignature = function(modelsToIgnore) { - var classClose, classOpen, prop, propertiesStr, returnVal, strong, strongClose, stronger, _i, _j, _len, _len1, _ref, _ref1; - propertiesStr = []; - _ref = this.properties; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - prop = _ref[_i]; - propertiesStr.push(prop.toString()); - } - strong = ''; - stronger = ''; - strongClose = ''; - classOpen = strong + this.name + ' {' + strongClose; - classClose = strong + '}' + strongClose; - returnVal = classOpen + '
' + propertiesStr.join(',
') + '
' + classClose; - if (!modelsToIgnore) { - modelsToIgnore = []; - } - modelsToIgnore.push(this); - _ref1 = this.properties; - for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { - prop = _ref1[_j]; - if ((prop.refModel != null) && modelsToIgnore.indexOf(prop.refModel) === -1) { - returnVal = returnVal + ('
' + prop.refModel.getMockSignature(modelsToIgnore)); - } - } - return returnVal; - }; - - SwaggerModel.prototype.createJSONSample = function(modelsToIgnore) { - var prop, result, _i, _len, _ref; - result = {}; - modelsToIgnore = modelsToIgnore || []; - modelsToIgnore.push(this.name); - _ref = this.properties; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - prop = _ref[_i]; - result[prop.name] = prop.getSampleValue(modelsToIgnore); - } - modelsToIgnore.pop(this.name); - return result; - }; - - return SwaggerModel; - - })(); - - SwaggerModelProperty = (function() { - function SwaggerModelProperty(name, obj) { - this.name = name; - 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; - if (obj.items != null) { - if (obj.items.type != null) { - this.refDataType = obj.items.type; - } - if (obj.items.$ref != null) { - this.refDataType = obj.items.$ref; - } - } - this.dataTypeWithRef = this.refDataType != null ? this.dataType + '[' + this.refDataType + ']' : this.dataType; - if (obj.allowableValues != null) { - this.valueType = obj.allowableValues.valueType; - this.values = obj.allowableValues.values; - if (this.values != null) { - this.valuesString = "'" + this.values.join("' or '") + "'"; - } - } - if (obj["enum"] != null) { - this.valueType = "string"; - this.values = obj["enum"]; - if (this.values != null) { - this.valueString = "'" + this.values.join("' or '") + "'"; - } - } - } - - SwaggerModelProperty.prototype.getSampleValue = function(modelsToIgnore) { - var result; - if ((this.refModel != null) && (modelsToIgnore[this.refModel.name] === 'undefined')) { - result = this.refModel.createJSONSample(modelsToIgnore); - } else { - if (this.isCollection) { - result = this.toSampleValue(this.refDataType); - } else { - result = this.toSampleValue(this.dataType); - } - } - if (this.isCollection) { - return [result]; - } else { - return result; - } - }; - - SwaggerModelProperty.prototype.toSampleValue = function(value) { - var result; - if (value === "integer") { - result = 0; - } else if (value === "boolean") { - result = false; - } else if (value === "double") { - result = 0.0; - } else if (value === "string") { - result = ""; - } else { - result = value; - } - return result; - }; - - SwaggerModelProperty.prototype.toString = function() { - var req, str; - req = this.required ? 'propReq' : 'propOpt'; - str = '' + this.name + ' (' + this.dataTypeWithRef + ''; - if (!this.required) { - str += ', optional'; - } - str += ')'; - if (this.values != null) { - str += " = ['" + this.values.join("' or '") + "']"; - } - if (this.descr != null) { - str += ': ' + this.descr + ''; - } - return str; - }; - - return SwaggerModelProperty; - - })(); - - this.SwaggerApi = SwaggerApi; - this.SwaggerResource = SwaggerResource; - this.SwaggerModelProperty = SwaggerModelProperty; - this.PasswordAuthorization = PasswordAuthorization; -}).call(this); +var e = typeof exports !== 'undefined' ? e : window; + +e.SwaggerHttp = SwaggerHttp; +e.SwaggerRequest = SwaggerRequest; +e.authorizations = new SwaggerAuthorizations(); +e.JQueryHttpClient = JQueryHttpClient; +e.ShredHttpClient = ShredHttpClient; +e.SwaggerOperation = SwaggerOperation; +e.SwaggerModel = SwaggerModel; +e.SwaggerModelProperty = SwaggerModelProperty; +e.SwaggerResource = SwaggerResource; +e.SwaggerApi = SwaggerApi; \ No newline at end of file From dc00ea84e081860dd273fc1cef05d1905581c6e9 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 11 Feb 2014 18:37:32 -0800 Subject: [PATCH 04/13] updated specs, jquery sppt --- lib/swagger-operation-spec.js | 6 +- lib/swagger.js | 129 ++++++++++++------------------ src/swagger-operation-spec.coffee | 6 +- 3 files changed, 56 insertions(+), 85 deletions(-) diff --git a/lib/swagger-operation-spec.js b/lib/swagger-operation-spec.js index 88e8eb01c..209e9d675 100644 --- a/lib/swagger-operation-spec.js +++ b/lib/swagger-operation-spec.js @@ -6,7 +6,7 @@ beforeEach(function() { var success; success = function() { - return console.log("success"); + return log("success"); }; window.authorizations.add("key", new ApiKeyAuthorization("api_key", "special-key", "header")); window.swagger = new SwaggerApi({ @@ -70,7 +70,7 @@ it("verifies the response messages from the get operation", function() { var operation, responseMessages; operation = swagger.pet.operations.getPetById; - console.log(operation); + log(operation); responseMessages = operation.responseMessages; expect(responseMessages).toBeDefined; expect(responseMessages.length).toBe(2); @@ -129,7 +129,7 @@ expect(parameters).toBeDefined; expect(parameters.length).toBe(1); param = parameters[0]; - console.log(param); + log(param); expect(param.name).toBe("tags"); expect(param.type).toBe("string"); expect(param.paramType).toBe("query"); diff --git a/lib/swagger.js b/lib/swagger.js index d56444cfd..6afce8fbd 100644 --- a/lib/swagger.js +++ b/lib/swagger.js @@ -10,51 +10,39 @@ log = function() { }; var SwaggerApi = function(url, options) { - if (options == null) { - options = {}; - } - if (url) { - if (url.url) { + this.url = null; + this.debug = false; + this.basePath = null; + this.authorizations = null; + this.authorizationScheme = null; + this.info = null; + this.useJQuery = true; + + options = (options||{}); + if (url) + if (url.url) options = url; - } else { + else this.url = url; - } - } else { + else options = url; - } - if (options.url != null) { + + if (options.url != null) this.url = options.url; - } - if (options.success != null) { + + if (options.success != null) this.success = options.success; - } + this.failure = options.failure != null ? options.failure : function() {}; this.progress = options.progress != null ? options.progress : function() {}; - if (options.success != null) { + if (options.success != null) this.build(); - } } -SwaggerApi.prototype.url = "http://api.wordnik.com/v4/resources.json"; - -SwaggerApi.prototype.debug = false; - -SwaggerApi.prototype.basePath = null; - -SwaggerApi.prototype.authorizations = null; - -SwaggerApi.prototype.authorizationScheme = null; - -SwaggerApi.prototype.info = null; - -SwaggerApi.prototype.useJQuery = null; - - SwaggerApi.prototype.build = function() { - var e, obj, - _this = this; + var _this = this; this.progress('fetching resource list: ' + this.url); - obj = { + var obj = { useJQuery: this.useJQuery, url: this.url, method: "get", @@ -73,9 +61,9 @@ SwaggerApi.prototype.build = function() { return _this.fail(response.status + ' : ' + response.statusText + ' ' + _this.url); } }, - response: function(response) { + response: function(resp) { var responseObj; - responseObj = JSON.parse(response.data); + responseObj = JSON.parse(resp.data); _this.swaggerVersion = responseObj.swaggerVersion; if (_this.swaggerVersion === "1.2") { return _this.buildFromSpec(responseObj); @@ -85,19 +73,13 @@ SwaggerApi.prototype.build = function() { } } }; - e = {}; - if (typeof window !== 'undefined') { - e = window; - } else { - e = exports; - } + var e = typeof window !== 'undefined' ? window : exports; e.authorizations.apply(obj); new SwaggerHttp().execute(obj); return this; }; SwaggerApi.prototype.buildFromSpec = function(response) { - var api, isApi, newName, operation, res, resource, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2; if (response.apiVersion != null) { this.apiVersion = response.apiVersion; } @@ -108,14 +90,12 @@ SwaggerApi.prototype.buildFromSpec = function(response) { if (response.info != null) { this.info = response.info; } - isApi = false; - _ref = response.apis; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - api = _ref[_i]; + var isApi = false; + for (var i = 0; i < response.apis.length; i++) { + var api = response.apis[i]; if (api.operations) { - _ref1 = api.operations; - for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { - operation = _ref1[_j]; + for (var j = 0; j < api.operations.length; j++) { + operation = api.operations[j]; isApi = true; } } @@ -128,15 +108,14 @@ SwaggerApi.prototype.buildFromSpec = function(response) { this.basePath = this.url; } if (isApi) { - newName = response.resourcePath.replace(/\//g, ''); + var newName = response.resourcePath.replace(/\//g, ''); this.resourcePath = response.resourcePath; res = new SwaggerResource(response, this); this.apis[newName] = res; this.apisArray.push(res); } else { - _ref2 = response.apis; - for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { - resource = _ref2[_k]; + for (var k = 0; k < response.apis.length; k++) { + var resource = response.apis[k]; res = new SwaggerResource(resource, this); this.apis[res.name] = res; this.apisArray.push(res); @@ -284,6 +263,7 @@ var SwaggerResource = function(resourceObj, api) { this.modelsArray = []; this.models = {}; this.rawModels = {}; + this.useJQuery = api.useJQuery; if ((resourceObj.apis != null) && (this.api.resourcePath != null)) { this.addApiDeclaration(resourceObj); @@ -315,21 +295,12 @@ var SwaggerResource = function(resourceObj, api) { } } }; - e = {}; - if (typeof window !== 'undefined') { - e = window; - } else { - e = exports; - } + var e = typeof window !== 'undefined' ? window : exports; e.authorizations.apply(obj); new SwaggerHttp().execute(obj); } } -SwaggerResource.prototype.api = null; -SwaggerResource.prototype.produces = null; -SwaggerResource.prototype.consumes = null; - SwaggerResource.prototype.getAbsoluteBasePath = function(relativeBasePath) { var parts, pos, url; url = this.api.basePath; @@ -447,20 +418,18 @@ SwaggerResource.prototype.sanitize = function(nickname) { }; SwaggerResource.prototype.help = function() { - var msg, operation, operation_name, parameter, _i, _len, _ref, _ref1, _results; - _ref = this.operations; - _results = []; - for (operation_name in _ref) { - operation = _ref[operation_name]; - msg = " " + operation.nickname; - _ref1 = operation.parameters; - for (_i = 0, _len = _ref1.length; _i < _len; _i++) { - parameter = _ref1[_i]; + var op = this.operations; + var output = []; + 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); } - _results.push(msg); + output.push(msg); } - return _results; + return output; }; var SwaggerModel = function(modelName, obj) { @@ -1070,16 +1039,18 @@ SwaggerRequest.prototype.asCurl = function() { /* * SwaggerHttp is a wrapper for executing requests */ -var SwaggerHttp = function(options) { - options = (options||{}); - this.useJQuery = options["useJQuery"]||false; -}; +var SwaggerHttp = function() {}; SwaggerHttp.prototype.execute = function(obj) { + obj = (obj||{ + useJQuery : this.isIE8() + }); + this.useJQuery = obj["useJQuery"]||false; if(this.useJQuery) return new JQueryHttpClient().execute(obj); else - return new ShredHttpClient().execute(obj); + throw "sorry!"; + // return new ShredHttpClient().execute(obj); } SwaggerHttp.prototype.isIE8 = function() { diff --git a/src/swagger-operation-spec.coffee b/src/swagger-operation-spec.coffee index 978d06473..4fee1aabd 100644 --- a/src/swagger-operation-spec.coffee +++ b/src/swagger-operation-spec.coffee @@ -4,7 +4,7 @@ describe 'Operations for version 1.2 spec', -> beforeEach -> success = -> - console.log "success" + log "success" window.authorizations.add "key", new ApiKeyAuthorization("api_key", "special-key", "header") window.swagger = new SwaggerApi({url: 'http://localhost:8002/api/api-docs', success: success}) waitsFor -> @@ -54,7 +54,7 @@ describe 'Operations for version 1.2 spec', -> it "verifies the response messages from the get operation", -> operation = swagger.pet.operations.getPetById - console.log operation + log operation responseMessages = operation.responseMessages expect(responseMessages).toBeDefined @@ -120,7 +120,7 @@ describe 'Operations for version 1.2 spec', -> expect(parameters.length).toBe 1 param = parameters[0] - console.log param + log param expect(param.name).toBe "tags" expect(param.type).toBe "string" expect(param.paramType).toBe "query" From d96b87d3845cd458cc39e55d61e587b1f9333e4e Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 11 Feb 2014 18:39:35 -0800 Subject: [PATCH 05/13] updated specs, jquery sppt --- src/swagger-api-listing-spec.coffee | 4 ++-- src/swagger-execution-spec.coffee | 4 ++-- src/swagger-http-spec.coffee | 6 +++--- src/swagger-model-spec.coffee | 4 ++-- src/swagger-request-spec.coffee | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/swagger-api-listing-spec.coffee b/src/swagger-api-listing-spec.coffee index d7ef54291..82a64ceb2 100644 --- a/src/swagger-api-listing-spec.coffee +++ b/src/swagger-api-listing-spec.coffee @@ -4,7 +4,7 @@ describe 'Swagger Api Listing for version 1.2 spec', -> beforeEach -> success = -> - console.log "success" + log "success" window.authorizations.add "key", new ApiKeyAuthorization("api_key", "special-key", "header") window.swagger = new SwaggerApi({url: 'http://localhost:8002/api/api-docs', success: success}) waitsFor -> @@ -42,5 +42,5 @@ describe 'Swagger Api Listing for version 1.2 spec', -> runs -> pet = JSON.parse(window.response.data) - console.log(pet) + log(pet) expect(pet.code).toNotBe 400 \ No newline at end of file diff --git a/src/swagger-execution-spec.coffee b/src/swagger-execution-spec.coffee index 4f4ca0a73..f5c8ec95f 100644 --- a/src/swagger-execution-spec.coffee +++ b/src/swagger-execution-spec.coffee @@ -4,7 +4,7 @@ describe 'SwaggerRequest for version 1.2 spec', -> beforeEach -> success = -> - console.log "success" + log "success" window.authorizations.add "key", new ApiKeyAuthorization("api_key", "special-key", "header") window.swagger = new SwaggerApi({url: 'http://localhost:8002/api/api-docs', success: success}) waitsFor -> @@ -40,5 +40,5 @@ describe 'SwaggerRequest for version 1.2 spec', -> runs -> pet = JSON.parse(window.response.data) - console.log(pet) + log(pet) expect(pet.code).toNotBe 400 diff --git a/src/swagger-http-spec.coffee b/src/swagger-http-spec.coffee index fa53ada04..82ab6a01a 100644 --- a/src/swagger-http-spec.coffee +++ b/src/swagger-http-spec.coffee @@ -4,7 +4,7 @@ describe 'SwaggerHttp for version 1.2 spec', -> beforeEach -> success = -> - console.log "success" + log "success" window.authorizations.add "key", new ApiKeyAuthorization("api_key", "special-key", "header") window.swagger = new SwaggerApi({url: 'http://localhost:8002/api/api-docs', success: success}) waitsFor -> @@ -92,7 +92,7 @@ describe 'SwaggerHttp for version 1.2 spec', -> runs -> obj = window.response - console.log obj + log obj expect(obj.method).toBe "POST" expect(obj.headers["Accept"]).toBe "application/json" expect(obj.headers["Content-Type"]).toBe "application/json" @@ -116,7 +116,7 @@ describe 'SwaggerHttp for version 1.2 spec', -> runs -> obj = window.response - console.log obj + log obj expect(obj.body).toBe "name=dog&status=very%20happy" expect(obj.method).toBe "POST" expect(obj.headers["Accept"]).toBe "application/json" diff --git a/src/swagger-model-spec.coffee b/src/swagger-model-spec.coffee index d5684554d..31a069025 100644 --- a/src/swagger-model-spec.coffee +++ b/src/swagger-model-spec.coffee @@ -52,5 +52,5 @@ describe 'Swagger models version 1.2 spec', -> it "verifies the Pet sample JSON", -> pet = window.swagger.apis.pet.models["Pet"] sample = pet.createJSONSample() - console.log sample - console.log JSON.stringify sample \ No newline at end of file + log sample + log JSON.stringify sample \ No newline at end of file diff --git a/src/swagger-request-spec.coffee b/src/swagger-request-spec.coffee index 04feb6dce..ef44a4884 100644 --- a/src/swagger-request-spec.coffee +++ b/src/swagger-request-spec.coffee @@ -4,7 +4,7 @@ describe 'SwaggerRequest for version 1.2 spec', -> beforeEach -> success = -> - console.log "success" + log "success" window.authorizations.add "key", new ApiKeyAuthorization("api_key", "special-key", "header") window.swagger = new SwaggerApi({url: 'http://localhost:8002/api/api-docs', success: success}) waitsFor -> @@ -105,7 +105,7 @@ describe 'SwaggerRequest for version 1.2 spec', -> runs -> pet = window.response.data - console.log pet + log pet it "handles redirects", -> params = {} From 0e8a2072c8fae893f3bb644631cd88bfa429882d Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 11 Feb 2014 18:41:17 -0800 Subject: [PATCH 06/13] updated specs, jquery sppt --- lib/swagger-api-listing-spec.js | 4 ++-- lib/swagger-execution-spec.js | 4 ++-- lib/swagger-http-spec.js | 6 +++--- lib/swagger-model-spec.js | 4 ++-- lib/swagger-request-spec.js | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/lib/swagger-api-listing-spec.js b/lib/swagger-api-listing-spec.js index f2efe97dd..b9ed4b61c 100644 --- a/lib/swagger-api-listing-spec.js +++ b/lib/swagger-api-listing-spec.js @@ -6,7 +6,7 @@ beforeEach(function() { var success; success = function() { - return console.log("success"); + return log("success"); }; window.authorizations.add("key", new ApiKeyAuthorization("api_key", "special-key", "header")); window.swagger = new SwaggerApi({ @@ -52,7 +52,7 @@ return runs(function() { var pet; pet = JSON.parse(window.response.data); - console.log(pet); + log(pet); return expect(pet.code).toNotBe(400); }); }); diff --git a/lib/swagger-execution-spec.js b/lib/swagger-execution-spec.js index caf110b07..8d2f0a419 100644 --- a/lib/swagger-execution-spec.js +++ b/lib/swagger-execution-spec.js @@ -6,7 +6,7 @@ beforeEach(function() { var success; success = function() { - return console.log("success"); + return log("success"); }; window.authorizations.add("key", new ApiKeyAuthorization("api_key", "special-key", "header")); window.swagger = new SwaggerApi({ @@ -53,7 +53,7 @@ return runs(function() { var pet; pet = JSON.parse(window.response.data); - console.log(pet); + log(pet); return expect(pet.code).toNotBe(400); }); }); diff --git a/lib/swagger-http-spec.js b/lib/swagger-http-spec.js index 474ab3be8..ccdd40bfc 100644 --- a/lib/swagger-http-spec.js +++ b/lib/swagger-http-spec.js @@ -6,7 +6,7 @@ beforeEach(function() { var success; success = function() { - return console.log("success"); + return log("success"); }; window.authorizations.add("key", new ApiKeyAuthorization("api_key", "special-key", "header")); window.swagger = new SwaggerApi({ @@ -105,7 +105,7 @@ return runs(function() { var obj; obj = window.response; - console.log(obj); + log(obj); expect(obj.method).toBe("POST"); expect(obj.headers["Accept"]).toBe("application/json"); expect(obj.headers["Content-Type"]).toBe("application/json"); @@ -130,7 +130,7 @@ return runs(function() { var obj; obj = window.response; - console.log(obj); + log(obj); expect(obj.body).toBe("name=dog&status=very%20happy"); expect(obj.method).toBe("POST"); expect(obj.headers["Accept"]).toBe("application/json"); diff --git a/lib/swagger-model-spec.js b/lib/swagger-model-spec.js index ee365f7bb..92537d5c6 100644 --- a/lib/swagger-model-spec.js +++ b/lib/swagger-model-spec.js @@ -55,8 +55,8 @@ var pet, sample; pet = window.swagger.apis.pet.models["Pet"]; sample = pet.createJSONSample(); - console.log(sample); - return console.log(JSON.stringify(sample)); + log(sample); + return log(JSON.stringify(sample)); }); }); }); diff --git a/lib/swagger-request-spec.js b/lib/swagger-request-spec.js index 1abb5e614..93aca4560 100644 --- a/lib/swagger-request-spec.js +++ b/lib/swagger-request-spec.js @@ -6,7 +6,7 @@ beforeEach(function() { var success; success = function() { - return console.log("success"); + return log("success"); }; window.authorizations.add("key", new ApiKeyAuthorization("api_key", "special-key", "header")); window.swagger = new SwaggerApi({ @@ -114,7 +114,7 @@ runs(function() { var pet; pet = window.response.data; - return console.log(pet); + return log(pet); }); it("handles redirects", function() { var opts, params; From 57a9eb59448fcbb68a94a3cfbe7516bbe8e5e42d Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 11 Feb 2014 21:13:52 -0800 Subject: [PATCH 07/13] fixed ie8 issues --- lib/swagger-operation-spec.js | 2 +- lib/swagger.js | 20 ++++++++++---------- src/swagger-operation-spec.coffee | 2 +- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/swagger-operation-spec.js b/lib/swagger-operation-spec.js index 209e9d675..4c6dd0698 100644 --- a/lib/swagger-operation-spec.js +++ b/lib/swagger-operation-spec.js @@ -216,7 +216,7 @@ return it("gets help() from the file upload operation", function() { var operation; operation = swagger.pet.operations.uploadFile; - return expect(operation.help().trim()).toBe("* additionalMetadata - Additional data to pass to server\n* file - file to upload"); + return expect(operation.help()).toBe("* additionalMetadata - Additional data to pass to server\n* file - file to upload"); }); }); }); diff --git a/lib/swagger.js b/lib/swagger.js index 6afce8fbd..35c644be7 100644 --- a/lib/swagger.js +++ b/lib/swagger.js @@ -6,7 +6,7 @@ var __bind = function(fn, me){ log = function() { if (window.console) - return console.log.apply(console, arguments); + return console.log(console, arguments); }; var SwaggerApi = function(url, options) { @@ -263,7 +263,7 @@ var SwaggerResource = function(resourceObj, api) { this.modelsArray = []; this.models = {}; this.rawModels = {}; - this.useJQuery = api.useJQuery; + this.useJQuery = (typeof api.useJQuery !== 'undefined' ? api.useJQuery : null); if ((resourceObj.apis != null) && (this.api.resourcePath != null)) { this.addApiDeclaration(resourceObj); @@ -880,10 +880,10 @@ SwaggerOperation.prototype.help = function() { return msg; }; -var SwaggerRequest = function(type, url, params, opts, successCallback, errorCallback, operation, execution) { +var SwaggerRequest = function(type, url, params, opts, successCallback, errorCallback, operation, execution) { var _this = this; var errors = []; - + this.useJQuery = (typeof operation.useJQuery !== 'undefined' ? operation.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.params = params; @@ -1042,15 +1042,15 @@ SwaggerRequest.prototype.asCurl = function() { var SwaggerHttp = function() {}; SwaggerHttp.prototype.execute = function(obj) { - obj = (obj||{ - useJQuery : this.isIE8() - }); - this.useJQuery = obj["useJQuery"]||false; + if(obj && (typeof obj.useJQuery === 'boolean')) + this.useJQuery = obj.useJQuery; + else + this.useJQuery = this.isIE8(); + if(this.useJQuery) return new JQueryHttpClient().execute(obj); else - throw "sorry!"; - // return new ShredHttpClient().execute(obj); + return new ShredHttpClient().execute(obj); } SwaggerHttp.prototype.isIE8 = function() { diff --git a/src/swagger-operation-spec.coffee b/src/swagger-operation-spec.coffee index 4fee1aabd..b8d2aeadf 100644 --- a/src/swagger-operation-spec.coffee +++ b/src/swagger-operation-spec.coffee @@ -216,4 +216,4 @@ describe 'Operations for version 1.2 spec', -> it "gets help() from the file upload operation", -> operation = swagger.pet.operations.uploadFile - expect(operation.help().trim()).toBe "* additionalMetadata - Additional data to pass to server\n* file - file to upload" + expect(operation.help()).toBe "* additionalMetadata - Additional data to pass to server\n* file - file to upload" From 7b8a3b4c127a081d1ca06fb7409e3f3c6ee91f37 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 11 Feb 2014 21:21:37 -0800 Subject: [PATCH 08/13] fixed dom parser error for ie --- lib/swagger-request-spec.js | 8 ++++++++ src/swagger-request-spec.coffee | 9 +++++++++ 2 files changed, 17 insertions(+) diff --git a/lib/swagger-request-spec.js b/lib/swagger-request-spec.js index 93aca4560..c7820d8ff 100644 --- a/lib/swagger-request-spec.js +++ b/lib/swagger-request-spec.js @@ -71,6 +71,14 @@ }); runs(function() { var data, parser, pet; + if (window.DOMParser) { + parser = new window.DOMParser(); + pet = parser.parseFromString(data, "text/xml"); + } else { + parser = new ActiveXObject("Microsoft.XMLDOM"); + parser.async = false; + pet = parser.loadXML(data); + } parser = new DOMParser(); data = window.response.data; pet = parser.parseFromString(data, "text/xml"); diff --git a/src/swagger-request-spec.coffee b/src/swagger-request-spec.coffee index ef44a4884..faa86c25c 100644 --- a/src/swagger-request-spec.coffee +++ b/src/swagger-request-spec.coffee @@ -62,6 +62,15 @@ describe 'SwaggerRequest for version 1.2 spec', -> window.response? runs -> + if window.DOMParser + parser = new window.DOMParser() + pet = parser.parseFromString(data, "text/xml") + + else + parser = new ActiveXObject("Microsoft.XMLDOM") + parser.async = false + pet = parser.loadXML(data) + parser = new DOMParser() data = window.response.data pet = parser.parseFromString( data, "text/xml" ) From 866f292672f6a69f2da77e0089670ab6d401c928 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 11 Feb 2014 21:22:40 -0800 Subject: [PATCH 09/13] fixed dom parser error for ie --- lib/swagger-request-spec.js | 4 +--- src/swagger-request-spec.coffee | 7 +------ 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/lib/swagger-request-spec.js b/lib/swagger-request-spec.js index c7820d8ff..74274bb9c 100644 --- a/lib/swagger-request-spec.js +++ b/lib/swagger-request-spec.js @@ -71,6 +71,7 @@ }); runs(function() { var data, parser, pet; + data = window.response.data; if (window.DOMParser) { parser = new window.DOMParser(); pet = parser.parseFromString(data, "text/xml"); @@ -79,9 +80,6 @@ parser.async = false; pet = parser.loadXML(data); } - parser = new DOMParser(); - data = window.response.data; - pet = parser.parseFromString(data, "text/xml"); return expect(pet).toBeDefined; }); it("fetches an object with plain text", function() { diff --git a/src/swagger-request-spec.coffee b/src/swagger-request-spec.coffee index faa86c25c..60d4c7634 100644 --- a/src/swagger-request-spec.coffee +++ b/src/swagger-request-spec.coffee @@ -62,21 +62,16 @@ describe 'SwaggerRequest for version 1.2 spec', -> window.response? runs -> + data = window.response.data if window.DOMParser parser = new window.DOMParser() pet = parser.parseFromString(data, "text/xml") - else parser = new ActiveXObject("Microsoft.XMLDOM") parser.async = false pet = parser.loadXML(data) - parser = new DOMParser() - data = window.response.data - pet = parser.parseFromString( data, "text/xml" ) - #pet = window.response expect(pet).toBeDefined - #expect(pet.id).toBe 1 it "fetches an object with plain text", -> params = {} From 65d5a3bd9bee334c2a4548c5d2b250ca3054b3b1 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 11 Feb 2014 21:27:26 -0800 Subject: [PATCH 10/13] more de-mangling --- lib/swagger.js | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/lib/swagger.js b/lib/swagger.js index 35c644be7..b69cd2df9 100644 --- a/lib/swagger.js +++ b/lib/swagger.js @@ -128,25 +128,21 @@ SwaggerApi.prototype.buildFromSpec = function(response) { }; SwaggerApi.prototype.buildFrom1_1Spec = function(response) { - var api, isApi, newName, operation, res, resource, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2; 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) { + if (response.apiVersion != null) this.apiVersion = response.apiVersion; - } this.apis = {}; this.apisArray = []; this.produces = response.produces; if (response.info != null) { this.info = response.info; } - isApi = false; - _ref = response.apis; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - api = _ref[_i]; + var isApi = false; + for (var i = 0; i < response.apis.length; i++) { + var api = response.apis[i]; if (api.operations) { - _ref1 = api.operations; - for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { - operation = _ref1[_j]; + for (var j = 0; j < api.operations.length; j++) { + operation = api.operations[j]; isApi = true; } } @@ -159,15 +155,14 @@ SwaggerApi.prototype.buildFrom1_1Spec = function(response) { this.basePath = this.url; } if (isApi) { - newName = response.resourcePath.replace(/\//g, ''); + var newName = response.resourcePath.replace(/\//g, ''); this.resourcePath = response.resourcePath; - res = new SwaggerResource(response, this); + var res = new SwaggerResource(response, this); this.apis[newName] = res; this.apisArray.push(res); } else { - _ref2 = response.apis; - for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { - resource = _ref2[_k]; + for (k = 0; k < response.apis.length; k++) { + resource = response.apis[k]; res = new SwaggerResource(resource, this); this.apis[res.name] = res; this.apisArray.push(res); From 2f9ebe16a08b424fbbc5a537cc78aee340203057 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 11 Feb 2014 22:06:17 -0800 Subject: [PATCH 11/13] added obj parsing for json response --- lib/swagger.js | 53 ++++++++++++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 21 deletions(-) diff --git a/lib/swagger.js b/lib/swagger.js index b69cd2df9..293547f75 100644 --- a/lib/swagger.js +++ b/lib/swagger.js @@ -4,9 +4,12 @@ var __bind = function(fn, me){ }; }; -log = function() { - if (window.console) - return console.log(console, arguments); +log = function(){ + log.history = log.history || []; + log.history.push(arguments); + if(this.console){ + console.log( Array.prototype.slice.call(arguments) ); + } }; var SwaggerApi = function(url, options) { @@ -16,7 +19,6 @@ var SwaggerApi = function(url, options) { this.authorizations = null; this.authorizationScheme = null; this.info = null; - this.useJQuery = true; options = (options||{}); if (url) @@ -62,8 +64,7 @@ SwaggerApi.prototype.build = function() { } }, response: function(resp) { - var responseObj; - responseObj = JSON.parse(resp.data); + var responseObj = resp.obj; _this.swaggerVersion = responseObj.swaggerVersion; if (_this.swaggerVersion === "1.2") { return _this.buildFromSpec(responseObj); @@ -73,7 +74,7 @@ SwaggerApi.prototype.build = function() { } } }; - var e = typeof window !== 'undefined' ? window : exports; + var e = (typeof window !== 'undefined' ? window : exports); e.authorizations.apply(obj); new SwaggerHttp().execute(obj); return this; @@ -284,8 +285,7 @@ var SwaggerResource = function(resourceObj, api) { return _this.api.fail("Unable to read api '" + _this.name + "' from path " + _this.url + " (server returned " + response.statusText + ")"); }, response: function(response) { - var responseObj; - responseObj = JSON.parse(response.data); + var responseObj = response.obj; return _this.addApiDeclaration(responseObj); } } @@ -406,6 +406,7 @@ SwaggerResource.prototype.addOperations = function(resource_path, ops, consumes, SwaggerResource.prototype.sanitize = function(nickname) { var op; op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|./?,\\'""-]/g, '_'); + //' op = op.replace(/((_){2,})/g, '_'); op = op.replace(/^(_)*/g, ''); op = op.replace(/([_])*$/g, ''); @@ -875,7 +876,7 @@ SwaggerOperation.prototype.help = function() { return msg; }; -var SwaggerRequest = function(type, url, params, opts, successCallback, errorCallback, operation, execution) { +var SwaggerRequest = function(type, url, params, opts, successCallback, errorCallback, operation, execution) { var _this = this; var errors = []; this.useJQuery = (typeof operation.useJQuery !== 'undefined' ? operation.useJQuery : null); @@ -1031,7 +1032,7 @@ SwaggerRequest.prototype.asCurl = function() { return "curl " + (results.join(" ")) + " " + this.url; }; -/* +/** * SwaggerHttp is a wrapper for executing requests */ var SwaggerHttp = function() {}; @@ -1108,6 +1109,10 @@ JQueryHttpClient.prototype.execute = function(obj) { headers: headers }; + if(response._headers["Content-Type"] && response._headers["Content-Type"].indexOf("application/json") == 0 && response.content.data !== "") { + out.obj = JSON.parse(response.responseText); + } + if(response.status >= 200 && response.status < 300) cb.response(out); else if(response.status === 0 || (response.status >= 400 && response.status < 599)) @@ -1171,35 +1176,41 @@ ShredHttpClient.prototype.execute = function(obj) { var cb = obj.on, res; var transform = function(response) { - return { + var out = { headers: response._headers, url: response.request.url, method: response.request.method, status: response.status, data: response.content.data }; + + if(response._headers["Content-Type"]) { + if(response._headers["Content-Type"].indexOf("application/json") == 0) { + if(response.content.data !== "") + out.obj = JSON.parse(response.content.data); + else + out.obj = {} + } + } + return out; }; res = { error: function(response) { - if (obj) { + if (obj) return cb.error(transform(response)); - } }, redirect: function(response) { - if (obj) { + if (obj) return cb.redirect(transform(response)); - } }, 307: function(response) { - if (obj) { + if (obj) return cb.redirect(transform(response)); - } }, response: function(response) { - if (obj) { + if (obj) return cb.response(transform(response)); - } } }; if (obj) { @@ -1279,7 +1290,7 @@ PasswordAuthorization.prototype.apply = function(obj, authorizations) { return true; }; -var e = typeof exports !== 'undefined' ? e : window; +var e = (typeof window !== 'undefined' ? window : exports); e.SwaggerHttp = SwaggerHttp; e.SwaggerRequest = SwaggerRequest; From 0e84b9184571ff79861a2ef9184e04623ac932bb Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 11 Feb 2014 22:24:09 -0800 Subject: [PATCH 12/13] cleaned up content-type detection --- lib/swagger.js | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/lib/swagger.js b/lib/swagger.js index 293547f75..455e5f464 100644 --- a/lib/swagger.js +++ b/lib/swagger.js @@ -281,12 +281,13 @@ var SwaggerResource = function(resourceObj, api) { accept: "application/json" }, on: { - error: function(response) { - return _this.api.fail("Unable to read api '" + _this.name + "' from path " + _this.url + " (server returned " + response.statusText + ")"); - }, response: function(response) { var responseObj = response.obj; 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 + ")"); } } }; @@ -552,7 +553,7 @@ SwaggerModelProperty.prototype.toSampleValue = function(value) { result = 0; } else if (value === "boolean") { result = false; - } else if (value === "double") { + } else if (value === "double" || value === "number") { result = 0.0; } else if (value === "string") { result = ""; @@ -563,9 +564,8 @@ SwaggerModelProperty.prototype.toSampleValue = function(value) { }; SwaggerModelProperty.prototype.toString = function() { - var req, str; - req = this.required ? 'propReq' : 'propOpt'; - str = '' + this.name + ' (' + this.dataTypeWithRef + ''; + var req = this.required ? 'propReq' : 'propOpt'; + var str = '' + this.name + ' (' + this.dataTypeWithRef + ''; if (!this.required) { str += ', optional'; } @@ -580,8 +580,7 @@ SwaggerModelProperty.prototype.toString = function() { }; var SwaggerOperation = function(nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations) { - var parameter, v, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _ref3, - _this = this; + var _this = this; var errors = []; this.nickname = (nickname||errors.push("SwaggerOperations must have a nickname.")); @@ -1184,8 +1183,10 @@ ShredHttpClient.prototype.execute = function(obj) { data: response.content.data }; - if(response._headers["Content-Type"]) { - if(response._headers["Content-Type"].indexOf("application/json") == 0) { + var contentType = (response._headers["content-type"]||response._headers["Content-Type"]||null) + + if(contentType != null) { + if(contentType.indexOf("application/json") == 0) { if(response.content.data !== "") out.obj = JSON.parse(response.content.data); else From 7bb12e63bb9d719b435a45db6e48b42f7776e1cb Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 12 Feb 2014 07:35:11 -0800 Subject: [PATCH 13/13] added checks for empty content --- lib/swagger.js | 20 ++++++++++---------- package.json | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/lib/swagger.js b/lib/swagger.js index 455e5f464..e2e1058a7 100644 --- a/lib/swagger.js +++ b/lib/swagger.js @@ -1,3 +1,6 @@ +// swagger.js +// version 2.0.13 + var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); @@ -940,14 +943,10 @@ var SwaggerRequest = function(type, url, params, opts, successCallback, errorCal } responseContentType = null; - if (this.type === "POST" || this.type === "GET" || this.type === "PATCH") { - if (this.opts.responseContentType) { - responseContentType = this.opts.responseContentType; - } else { - responseContentType = "application/json"; - } + if (this.opts.responseContentType) { + responseContentType = this.opts.responseContentType; } else { - responseContentType = null; + responseContentType = "application/json"; } if (responseContentType && this.operation.produces) { if (this.operation.produces[responseContentType] === 'undefined') { @@ -1108,7 +1107,8 @@ JQueryHttpClient.prototype.execute = function(obj) { headers: headers }; - if(response._headers["Content-Type"] && response._headers["Content-Type"].indexOf("application/json") == 0 && response.content.data !== "") { + if(response._headers["Content-Type"] && response._headers["Content-Type"].indexOf("application/json") == 0 && + response.content.data && response.content.data !== "") { out.obj = JSON.parse(response.responseText); } @@ -1187,7 +1187,7 @@ ShredHttpClient.prototype.execute = function(obj) { if(contentType != null) { if(contentType.indexOf("application/json") == 0) { - if(response.content.data !== "") + if(response.content.data && response.content.data !== "") out.obj = JSON.parse(response.content.data); else out.obj = {} @@ -1302,4 +1302,4 @@ e.SwaggerOperation = SwaggerOperation; e.SwaggerModel = SwaggerModel; e.SwaggerModelProperty = SwaggerModelProperty; e.SwaggerResource = SwaggerResource; -e.SwaggerApi = SwaggerApi; \ No newline at end of file +e.SwaggerApi = SwaggerApi; diff --git a/package.json b/package.json index c20acf990..998fe429c 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ } ], "description": "swagger.js is a javascript client for use with swaggering APIs.", - "version": "2.0.12", + "version": "2.0.13", "homepage": "http://swagger.wordnik.com", "repository": { "type": "git",