swagger-client.js 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932
  1. /**
  2. * swagger-client - swagger.js is a javascript client for use with swaggering APIs.
  3. * @version v2.1.1-M1
  4. * @link http://swagger.io
  5. * @license apache 2.0
  6. */
  7. (function(){
  8. var ArrayModel = function(definition) {
  9. this.name = "arrayModel";
  10. this.definition = definition || {};
  11. this.properties = [];
  12. var requiredFields = definition.enum || [];
  13. var innerType = definition.items;
  14. if(innerType) {
  15. if(innerType.type) {
  16. this.type = typeFromJsonSchema(innerType.type, innerType.format);
  17. }
  18. else {
  19. this.ref = innerType.$ref;
  20. }
  21. }
  22. return this;
  23. };
  24. ArrayModel.prototype.createJSONSample = function(modelsToIgnore) {
  25. var result;
  26. modelsToIgnore = (modelsToIgnore||{});
  27. if(this.type) {
  28. result = this.type;
  29. }
  30. else if (this.ref) {
  31. var name = simpleRef(this.ref);
  32. if(typeof modelsToIgnore[name] === 'undefined') {
  33. modelsToIgnore[name] = this;
  34. result = models[name].createJSONSample(modelsToIgnore);
  35. }
  36. else {
  37. return name;
  38. }
  39. }
  40. return [ result ];
  41. };
  42. ArrayModel.prototype.getSampleValue = function(modelsToIgnore) {
  43. var result;
  44. modelsToIgnore = (modelsToIgnore || {});
  45. if(this.type) {
  46. result = type;
  47. }
  48. else if (this.ref) {
  49. var name = simpleRef(this.ref);
  50. result = models[name].getSampleValue(modelsToIgnore);
  51. }
  52. return [ result ];
  53. };
  54. ArrayModel.prototype.getMockSignature = function(modelsToIgnore) {
  55. var propertiesStr = [];
  56. if(this.ref) {
  57. return models[simpleRef(this.ref)].getMockSignature();
  58. }
  59. };
  60. /**
  61. * SwaggerAuthorizations applys the correct authorization to an operation being executed
  62. */
  63. var SwaggerAuthorizations = function() {
  64. this.authz = {};
  65. };
  66. SwaggerAuthorizations.prototype.add = function(name, auth) {
  67. this.authz[name] = auth;
  68. return auth;
  69. };
  70. SwaggerAuthorizations.prototype.remove = function(name) {
  71. return delete this.authz[name];
  72. };
  73. SwaggerAuthorizations.prototype.apply = function (obj, authorizations) {
  74. var status = null;
  75. var key, value, result;
  76. // if the "authorizations" key is undefined, or has an empty array, add all keys
  77. if (typeof authorizations === 'undefined' || Object.keys(authorizations).length == 0) {
  78. for (key in this.authz) {
  79. value = this.authz[key];
  80. result = value.apply(obj, authorizations);
  81. if (result === true)
  82. status = true;
  83. }
  84. }
  85. else {
  86. // 2.0 support
  87. if (Array.isArray(authorizations)) {
  88. for (var i = 0; i < authorizations.length; i++) {
  89. var auth = authorizations[i];
  90. for (name in auth) {
  91. for (key in this.authz) {
  92. if (key == name) {
  93. value = this.authz[key];
  94. result = value.apply(obj, authorizations);
  95. if (result === true)
  96. status = true;
  97. }
  98. }
  99. }
  100. }
  101. }
  102. else {
  103. // 1.2 support
  104. for (name in authorizations) {
  105. for (key in this.authz) {
  106. if (key == name) {
  107. value = this.authz[key];
  108. result = value.apply(obj, authorizations);
  109. if (result === true)
  110. status = true;
  111. }
  112. }
  113. }
  114. }
  115. }
  116. return status;
  117. };
  118. /**
  119. * ApiKeyAuthorization allows a query param or header to be injected
  120. */
  121. var ApiKeyAuthorization = function(name, value, type) {
  122. this.name = name;
  123. this.value = value;
  124. this.type = type;
  125. };
  126. ApiKeyAuthorization.prototype.apply = function(obj, authorizations) {
  127. if (this.type === "query") {
  128. if (obj.url.indexOf('?') > 0)
  129. obj.url = obj.url + "&" + this.name + "=" + this.value;
  130. else
  131. obj.url = obj.url + "?" + this.name + "=" + this.value;
  132. return true;
  133. } else if (this.type === "header") {
  134. obj.headers[this.name] = this.value;
  135. return true;
  136. }
  137. };
  138. var CookieAuthorization = function(cookie) {
  139. this.cookie = cookie;
  140. };
  141. CookieAuthorization.prototype.apply = function(obj, authorizations) {
  142. obj.cookieJar = obj.cookieJar || CookieJar();
  143. obj.cookieJar.setCookie(this.cookie);
  144. return true;
  145. };
  146. /**
  147. * Password Authorization is a basic auth implementation
  148. */
  149. var PasswordAuthorization = function(name, username, password) {
  150. this.name = name;
  151. this.username = username;
  152. this.password = password;
  153. this._btoa = null;
  154. if (typeof window !== 'undefined')
  155. this._btoa = btoa;
  156. else
  157. this._btoa = require("btoa");
  158. };
  159. PasswordAuthorization.prototype.apply = function(obj, authorizations) {
  160. var base64encoder = this._btoa;
  161. obj.headers.Authorization = "Basic " + base64encoder(this.username + ":" + this.password);
  162. return true;
  163. };
  164. var __bind = function(fn, me){
  165. return function(){
  166. return fn.apply(me, arguments);
  167. };
  168. };
  169. fail = function(message) {
  170. log(message);
  171. };
  172. log = function(){
  173. log.history = log.history || [];
  174. log.history.push(arguments);
  175. if(this.console){
  176. console.log( Array.prototype.slice.call(arguments)[0] );
  177. }
  178. };
  179. if (!Array.prototype.indexOf) {
  180. Array.prototype.indexOf = function(obj, start) {
  181. for (var i = (start || 0), j = this.length; i < j; i++) {
  182. if (this[i] === obj) { return i; }
  183. }
  184. return -1;
  185. };
  186. }
  187. /**
  188. * allows override of the default value based on the parameter being
  189. * supplied
  190. **/
  191. var applyParameterMacro = function (operation, parameter) {
  192. var e = (typeof window !== 'undefined' ? window : exports);
  193. if(e.parameterMacro)
  194. return e.parameterMacro(operation, parameter);
  195. else
  196. return parameter.defaultValue;
  197. };
  198. /**
  199. * allows overriding the default value of an model property
  200. **/
  201. var applyModelPropertyMacro = function (model, property) {
  202. var e = (typeof window !== 'undefined' ? window : exports);
  203. if(e.modelPropertyMacro)
  204. return e.modelPropertyMacro(model, property);
  205. else
  206. return property.defaultValue;
  207. };
  208. /**
  209. * PrimitiveModel
  210. **/
  211. var PrimitiveModel = function(definition) {
  212. this.name = "name";
  213. this.definition = definition || {};
  214. this.properties = [];
  215. var requiredFields = definition.enum || [];
  216. this.type = typeFromJsonSchema(definition.type, definition.format);
  217. };
  218. PrimitiveModel.prototype.createJSONSample = function(modelsToIgnore) {
  219. var result = this.type;
  220. return result;
  221. };
  222. PrimitiveModel.prototype.getSampleValue = function() {
  223. var result = this.type;
  224. return null;
  225. };
  226. PrimitiveModel.prototype.getMockSignature = function(modelsToIgnore) {
  227. var propertiesStr = [];
  228. var i, prop;
  229. for (i = 0; i < this.properties.length; i++) {
  230. prop = this.properties[i];
  231. propertiesStr.push(prop.toString());
  232. }
  233. var strong = '<span class="strong">';
  234. var stronger = '<span class="stronger">';
  235. var strongClose = '</span>';
  236. var classOpen = strong + this.name + ' {' + strongClose;
  237. var classClose = strong + '}' + strongClose;
  238. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  239. if (!modelsToIgnore)
  240. modelsToIgnore = {};
  241. modelsToIgnore[this.name] = this;
  242. for (i = 0; i < this.properties.length; i++) {
  243. prop = this.properties[i];
  244. var ref = prop.$ref;
  245. var model = models[ref];
  246. if (model && typeof modelsToIgnore[ref] === 'undefined') {
  247. returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
  248. }
  249. }
  250. return returnVal;
  251. };
  252. var SwaggerClient = function(url, options) {
  253. this.isBuilt = false;
  254. this.url = null;
  255. this.debug = false;
  256. this.basePath = null;
  257. this.modelsArray = [];
  258. this.authorizations = null;
  259. this.authorizationScheme = null;
  260. this.isValid = false;
  261. this.info = null;
  262. this.useJQuery = false;
  263. if(typeof url !== 'undefined')
  264. return this.initialize(url, options);
  265. };
  266. SwaggerClient.prototype.initialize = function (url, options) {
  267. this.models = models;
  268. options = (options||{});
  269. if(typeof url === 'string')
  270. this.url = url;
  271. else if(typeof url === 'object') {
  272. options = url;
  273. this.url = options.url;
  274. }
  275. this.swaggerRequstHeaders = options.swaggerRequstHeaders || 'application/json;charset=utf-8,*/*';
  276. this.defaultSuccessCallback = options.defaultSuccessCallback || null;
  277. this.defaultErrorCallback = options.defaultErrorCallback || null;
  278. if (typeof options.success === 'function')
  279. this.success = options.success;
  280. if (options.useJQuery)
  281. this.useJQuery = options.useJQuery;
  282. if (options.authorizations) {
  283. this.clientAuthorizations = options.authorizations;
  284. } else {
  285. var e = (typeof window !== 'undefined' ? window : exports);
  286. this.clientAuthorizations = e.authorizations;
  287. }
  288. this.supportedSubmitMethods = options.supportedSubmitMethods || [];
  289. this.failure = options.failure || function() {};
  290. this.progress = options.progress || function() {};
  291. this.spec = options.spec;
  292. this.options = options;
  293. if (typeof options.success === 'function') {
  294. this.build();
  295. }
  296. };
  297. SwaggerClient.prototype.build = function(mock) {
  298. if (this.isBuilt) return this;
  299. var self = this;
  300. this.progress('fetching resource list: ' + this.url);
  301. var obj = {
  302. useJQuery: this.useJQuery,
  303. url: this.url,
  304. method: "get",
  305. headers: {
  306. accept: this.swaggerRequstHeaders
  307. },
  308. on: {
  309. error: function(response) {
  310. if (self.url.substring(0, 4) !== 'http')
  311. return self.fail('Please specify the protocol for ' + self.url);
  312. else if (response.status === 0)
  313. return self.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.');
  314. else if (response.status === 404)
  315. return self.fail('Can\'t read swagger JSON from ' + self.url);
  316. else
  317. return self.fail(response.status + ' : ' + response.statusText + ' ' + self.url);
  318. },
  319. response: function(resp) {
  320. var responseObj = resp.obj || JSON.parse(resp.data);
  321. self.swaggerVersion = responseObj.swaggerVersion;
  322. if(responseObj.swagger && parseInt(responseObj.swagger) === 2) {
  323. self.swaggerVersion = responseObj.swagger;
  324. self.buildFromSpec(responseObj);
  325. self.isValid = true;
  326. }
  327. else {
  328. if (self.swaggerVersion === '1.2') {
  329. return self.buildFrom1_2Spec(responseObj);
  330. } else {
  331. return self.buildFrom1_1Spec(responseObj);
  332. }
  333. }
  334. }
  335. }
  336. };
  337. if(this.spec) {
  338. setTimeout(function() { self.buildFromSpec(self.spec); }, 10);
  339. }
  340. else {
  341. var e = (typeof window !== 'undefined' ? window : exports);
  342. var status = e.authorizations.apply(obj);
  343. if(mock)
  344. return obj;
  345. new SwaggerHttp().execute(obj);
  346. }
  347. return this;
  348. };
  349. SwaggerClient.prototype.buildFromSpec = function(response) {
  350. if(this.isBuilt) return this;
  351. this.info = response.info || {};
  352. this.title = response.title || '';
  353. this.host = response.host || '';
  354. this.schemes = response.schemes || [];
  355. this.basePath = response.basePath || '';
  356. this.apis = {};
  357. this.apisArray = [];
  358. this.consumes = response.consumes;
  359. this.produces = response.produces;
  360. this.securityDefinitions = response.securityDefinitions;
  361. // legacy support
  362. this.authSchemes = response.securityDefinitions;
  363. var location;
  364. if(typeof this.url === 'string') {
  365. location = this.parseUri(this.url);
  366. }
  367. if(typeof this.schemes === 'undefined' || this.schemes.length === 0) {
  368. this.scheme = location.scheme || 'http';
  369. }
  370. else {
  371. this.scheme = this.schemes[0];
  372. }
  373. if(typeof this.host === 'undefined' || this.host === '') {
  374. this.host = location.host;
  375. if (location.port) {
  376. this.host = this.host + ':' + location.port;
  377. }
  378. }
  379. this.definitions = response.definitions;
  380. var key;
  381. for(key in this.definitions) {
  382. var model = new Model(key, this.definitions[key]);
  383. if(model) {
  384. models[key] = model;
  385. }
  386. }
  387. // get paths, create functions for each operationId
  388. var path;
  389. var operations = [];
  390. for(path in response.paths) {
  391. if(typeof response.paths[path] === 'object') {
  392. var httpMethod;
  393. for(httpMethod in response.paths[path]) {
  394. if(['delete', 'get', 'head', 'options', 'patch', 'post', 'put'].indexOf(httpMethod) === -1) {
  395. continue;
  396. }
  397. var operation = response.paths[path][httpMethod];
  398. var tags = operation.tags;
  399. if(typeof tags === 'undefined') {
  400. operation.tags = [ 'default' ];
  401. tags = operation.tags;
  402. }
  403. var operationId = this.idFromOp(path, httpMethod, operation);
  404. var operationObject = new Operation (
  405. this,
  406. operation.scheme,
  407. operationId,
  408. httpMethod,
  409. path,
  410. operation,
  411. this.definitions
  412. );
  413. // bind this operation's execute command to the api
  414. if(tags.length > 0) {
  415. var i;
  416. for(i = 0; i < tags.length; i++) {
  417. var tag = this.tagFromLabel(tags[i]);
  418. var operationGroup = this[tag];
  419. if(typeof operationGroup === 'undefined') {
  420. this[tag] = [];
  421. operationGroup = this[tag];
  422. operationGroup.operations = {};
  423. operationGroup.label = tag;
  424. operationGroup.apis = [];
  425. this[tag].help = this.help.bind(operationGroup);
  426. this.apisArray.push(new OperationGroup(tag, operationObject));
  427. }
  428. operationGroup[operationId] = operationObject.execute.bind(operationObject);
  429. operationGroup[operationId].help = operationObject.help.bind(operationObject);
  430. operationGroup.apis.push(operationObject);
  431. operationGroup.operations[operationId] = operationObject;
  432. // legacy UI feature
  433. var j;
  434. var api;
  435. for(j = 0; j < this.apisArray.length; j++) {
  436. if(this.apisArray[j].tag === tag) {
  437. api = this.apisArray[j];
  438. }
  439. }
  440. if(api) {
  441. api.operationsArray.push(operationObject);
  442. }
  443. }
  444. }
  445. else {
  446. log('no group to bind to');
  447. }
  448. }
  449. }
  450. }
  451. this.isBuilt = true;
  452. if (this.success)
  453. this.success();
  454. return this;
  455. };
  456. SwaggerClient.prototype.parseUri = function(uri) {
  457. var urlParseRE = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/;
  458. var parts = urlParseRE.exec(uri);
  459. return {
  460. scheme: parts[4].replace(':',''),
  461. host: parts[11],
  462. port: parts[12],
  463. path: parts[15]
  464. };
  465. };
  466. SwaggerClient.prototype.help = function() {
  467. var i;
  468. log('operations for the "' + this.label + '" tag');
  469. for(i = 0; i < this.apis.length; i++) {
  470. var api = this.apis[i];
  471. log(' * ' + api.nickname + ': ' + api.operation.summary);
  472. }
  473. };
  474. SwaggerClient.prototype.tagFromLabel = function(label) {
  475. return label;
  476. };
  477. SwaggerClient.prototype.idFromOp = function(path, httpMethod, op) {
  478. var opId = op.operationId || (path.substring(1) + '_' + httpMethod);
  479. return opId.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()\+\s]/g,'_');
  480. };
  481. SwaggerClient.prototype.fail = function(message) {
  482. this.failure(message);
  483. throw message;
  484. };
  485. var OperationGroup = function(tag, operation) {
  486. this.tag = tag;
  487. this.path = tag;
  488. this.name = tag;
  489. this.operation = operation;
  490. this.operationsArray = [];
  491. this.description = operation.description || "";
  492. };
  493. var Operation = function(parent, scheme, operationId, httpMethod, path, args, definitions) {
  494. var errors = [];
  495. parent = parent||{};
  496. args = args||{};
  497. this.operations = {};
  498. this.operation = args;
  499. this.deprecated = args.deprecated;
  500. this.consumes = args.consumes;
  501. this.produces = args.produces;
  502. this.parent = parent;
  503. this.host = parent.host || 'localhost';
  504. this.schemes = parent.schemes;
  505. this.scheme = scheme || parent.scheme || 'http';
  506. this.basePath = parent.basePath || '/';
  507. this.nickname = (operationId||errors.push('Operations must have a nickname.'));
  508. this.method = (httpMethod||errors.push('Operation ' + operationId + ' is missing method.'));
  509. this.path = (path||errors.push('Operation ' + this.nickname + ' is missing path.'));
  510. this.parameters = args !== null ? (args.parameters||[]) : {};
  511. this.summary = args.summary || '';
  512. this.responses = (args.responses||{});
  513. this.type = null;
  514. this.security = args.security;
  515. this.authorizations = args.security;
  516. this.description = args.description;
  517. this.useJQuery = parent.useJQuery;
  518. if(definitions) {
  519. // add to global models
  520. var key;
  521. for(key in this.definitions) {
  522. var model = new Model(key, definitions[key]);
  523. if(model) {
  524. models[key] = model;
  525. }
  526. }
  527. }
  528. var i;
  529. for(i = 0; i < this.parameters.length; i++) {
  530. var param = this.parameters[i];
  531. if(param.type === 'array') {
  532. param.isList = true;
  533. param.allowMultiple = true;
  534. }
  535. var innerType = this.getType(param);
  536. if(innerType && innerType.toString().toLowerCase() === 'boolean') {
  537. param.allowableValues = {};
  538. param.isList = true;
  539. param['enum'] = ["true", "false"];
  540. }
  541. if(typeof param['enum'] !== 'undefined') {
  542. var id;
  543. param.allowableValues = {};
  544. param.allowableValues.values = [];
  545. param.allowableValues.descriptiveValues = [];
  546. for(id = 0; id < param['enum'].length; id++) {
  547. var value = param['enum'][id];
  548. var isDefault = (value === param.default) ? true : false;
  549. param.allowableValues.values.push(value);
  550. param.allowableValues.descriptiveValues.push({value : value, isDefault: isDefault});
  551. }
  552. }
  553. if(param.type === 'array') {
  554. innerType = [innerType];
  555. if(typeof param.allowableValues === 'undefined') {
  556. // can't show as a list if no values to select from
  557. delete param.isList;
  558. delete param.allowMultiple;
  559. }
  560. }
  561. param.signature = this.getModelSignature(innerType, models).toString();
  562. param.sampleJSON = this.getModelSampleJSON(innerType, models);
  563. param.responseClassSignature = param.signature;
  564. }
  565. var defaultResponseCode, response, model, responses = this.responses;
  566. if(responses['200']) {
  567. response = responses['200'];
  568. defaultResponseCode = '200';
  569. }
  570. else if(responses['201']) {
  571. response = responses['201'];
  572. defaultResponseCode = '201';
  573. }
  574. else if(responses['202']) {
  575. response = responses['202'];
  576. defaultResponseCode = '202';
  577. }
  578. else if(responses['203']) {
  579. response = responses['203'];
  580. defaultResponseCode = '203';
  581. }
  582. else if(responses['204']) {
  583. response = responses['204'];
  584. defaultResponseCode = '204';
  585. }
  586. else if(responses['205']) {
  587. response = responses['205'];
  588. defaultResponseCode = '205';
  589. }
  590. else if(responses['206']) {
  591. response = responses['206'];
  592. defaultResponseCode = '206';
  593. }
  594. else if(responses['default']) {
  595. response = responses['default'];
  596. defaultResponseCode = 'default';
  597. }
  598. if(response && response.schema) {
  599. var resolvedModel = this.resolveModel(response.schema, definitions);
  600. delete responses[defaultResponseCode];
  601. if(resolvedModel) {
  602. this.successResponse = {};
  603. this.successResponse[defaultResponseCode] = resolvedModel;
  604. }
  605. else {
  606. this.successResponse = {};
  607. this.successResponse[defaultResponseCode] = response.schema.type;
  608. }
  609. this.type = response;
  610. }
  611. if (errors.length > 0) {
  612. if(this.resource && this.resource.api && this.resource.api.fail)
  613. this.resource.api.fail(errors);
  614. }
  615. return this;
  616. };
  617. OperationGroup.prototype.sort = function(sorter) {
  618. };
  619. Operation.prototype.getType = function (param) {
  620. var type = param.type;
  621. var format = param.format;
  622. var isArray = false;
  623. var str;
  624. if(type === 'integer' && format === 'int32')
  625. str = 'integer';
  626. else if(type === 'integer' && format === 'int64')
  627. str = 'long';
  628. else if(type === 'integer')
  629. str = 'integer';
  630. else if(type === 'string' && format === 'date-time')
  631. str = 'date-time';
  632. else if(type === 'string' && format === 'date')
  633. str = 'date';
  634. else if(type === 'number' && format === 'float')
  635. str = 'float';
  636. else if(type === 'number' && format === 'double')
  637. str = 'double';
  638. else if(type === 'number')
  639. str = 'double';
  640. else if(type === 'boolean')
  641. str = 'boolean';
  642. else if(type === 'string')
  643. str = 'string';
  644. else if(type === 'array') {
  645. isArray = true;
  646. if(param.items)
  647. str = this.getType(param.items);
  648. }
  649. if(param.$ref)
  650. str = param.$ref;
  651. var schema = param.schema;
  652. if(schema) {
  653. var ref = schema.$ref;
  654. if(ref) {
  655. ref = simpleRef(ref);
  656. if(isArray)
  657. return [ ref ];
  658. else
  659. return ref;
  660. }
  661. else
  662. return this.getType(schema);
  663. }
  664. if(isArray)
  665. return [ str ];
  666. else
  667. return str;
  668. };
  669. Operation.prototype.resolveModel = function (schema, definitions) {
  670. if(typeof schema.$ref !== 'undefined') {
  671. var ref = schema.$ref;
  672. if(ref.indexOf('#/definitions/') === 0)
  673. ref = ref.substring('#/definitions/'.length);
  674. if(definitions[ref]) {
  675. return new Model(ref, definitions[ref]);
  676. }
  677. }
  678. if(schema.type === 'array')
  679. return new ArrayModel(schema);
  680. else
  681. return null;
  682. };
  683. Operation.prototype.help = function(dontPrint) {
  684. var out = this.nickname + ': ' + this.summary + '\n';
  685. for(var i = 0; i < this.parameters.length; i++) {
  686. var param = this.parameters[i];
  687. var typeInfo = typeFromJsonSchema(param.type, param.format);
  688. out += '\n * ' + param.name + ' (' + typeInfo + '): ' + param.description;
  689. }
  690. if(typeof dontPrint === 'undefined')
  691. log(out);
  692. return out;
  693. };
  694. Operation.prototype.getModelSignature = function(type, definitions) {
  695. var isPrimitive, listType;
  696. if(type instanceof Array) {
  697. listType = true;
  698. type = type[0];
  699. }
  700. else if(typeof type === 'undefined')
  701. type = 'undefined';
  702. if(type === 'string')
  703. isPrimitive = true;
  704. else
  705. isPrimitive = (listType && definitions[listType]) || (definitions[type]) ? false : true;
  706. if (isPrimitive) {
  707. if(listType)
  708. return 'Array[' + type + ']';
  709. else
  710. return type.toString();
  711. } else {
  712. if (listType)
  713. return 'Array[' + definitions[type].getMockSignature() + ']';
  714. else
  715. return definitions[type].getMockSignature();
  716. }
  717. };
  718. Operation.prototype.supportHeaderParams = function () {
  719. return true;
  720. };
  721. Operation.prototype.supportedSubmitMethods = function () {
  722. return this.parent.supportedSubmitMethods;
  723. };
  724. Operation.prototype.getHeaderParams = function (args) {
  725. var headers = this.setContentTypes(args, {});
  726. for(var i = 0; i < this.parameters.length; i++) {
  727. var param = this.parameters[i];
  728. if(typeof args[param.name] !== 'undefined') {
  729. if (param.in === 'header') {
  730. var value = args[param.name];
  731. if(Array.isArray(value))
  732. value = this.encodePathCollection(param.collectionFormat, param.name, value);
  733. else
  734. value = this.encodePathParam(value);
  735. headers[param.name] = value;
  736. }
  737. }
  738. }
  739. return headers;
  740. };
  741. Operation.prototype.urlify = function (args) {
  742. var formParams = {};
  743. var requestUrl = this.path;
  744. // grab params from the args, build the querystring along the way
  745. var querystring = '';
  746. for(var i = 0; i < this.parameters.length; i++) {
  747. var param = this.parameters[i];
  748. if(typeof args[param.name] !== 'undefined') {
  749. if(param.in === 'path') {
  750. var reg = new RegExp('\{' + param.name + '\}', 'gi');
  751. var value = args[param.name];
  752. if(Array.isArray(value))
  753. value = this.encodePathCollection(param.collectionFormat, param.name, value);
  754. else
  755. value = this.encodePathParam(value);
  756. requestUrl = requestUrl.replace(reg, value);
  757. }
  758. else if (param.in === 'query' && typeof args[param.name] !== 'undefined') {
  759. if(querystring === '')
  760. querystring += '?';
  761. else
  762. querystring += '&';
  763. if(typeof param.collectionFormat !== 'undefined') {
  764. var qp = args[param.name];
  765. if(Array.isArray(qp))
  766. querystring += this.encodeQueryCollection(param.collectionFormat, param.name, qp);
  767. else
  768. querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
  769. }
  770. else
  771. querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
  772. }
  773. else if (param.in === 'formData')
  774. formParams[param.name] = args[param.name];
  775. }
  776. }
  777. var url = this.scheme + '://' + this.host;
  778. if(this.basePath !== '/')
  779. url += this.basePath;
  780. return url + requestUrl + querystring;
  781. };
  782. Operation.prototype.getMissingParams = function(args) {
  783. var missingParams = [];
  784. // check required params, track the ones that are missing
  785. var i;
  786. for(i = 0; i < this.parameters.length; i++) {
  787. var param = this.parameters[i];
  788. if(param.required === true) {
  789. if(typeof args[param.name] === 'undefined')
  790. missingParams = param.name;
  791. }
  792. }
  793. return missingParams;
  794. };
  795. Operation.prototype.getBody = function(headers, args) {
  796. var formParams = {};
  797. var body;
  798. for(var i = 0; i < this.parameters.length; i++) {
  799. var param = this.parameters[i];
  800. if(typeof args[param.name] !== 'undefined') {
  801. if (param.in === 'body') {
  802. body = args[param.name];
  803. } else if(param.in === 'formData') {
  804. formParams[param.name] = args[param.name];
  805. }
  806. }
  807. }
  808. // handle form params
  809. if(headers['Content-Type'] === 'application/x-www-form-urlencoded') {
  810. var encoded = "";
  811. var key;
  812. for(key in formParams) {
  813. value = formParams[key];
  814. if(typeof value !== 'undefined'){
  815. if(encoded !== "")
  816. encoded += "&";
  817. encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
  818. }
  819. }
  820. body = encoded;
  821. }
  822. return body;
  823. };
  824. /**
  825. * gets sample response for a single operation
  826. **/
  827. Operation.prototype.getModelSampleJSON = function(type, models) {
  828. var isPrimitive, listType, sampleJson;
  829. listType = (type instanceof Array);
  830. isPrimitive = models[type] ? false : true;
  831. sampleJson = isPrimitive ? void 0 : models[type].createJSONSample();
  832. if (sampleJson) {
  833. sampleJson = listType ? [sampleJson] : sampleJson;
  834. if(typeof sampleJson == 'string')
  835. return sampleJson;
  836. else if(typeof sampleJson === 'object') {
  837. var t = sampleJson;
  838. if(sampleJson instanceof Array && sampleJson.length > 0) {
  839. t = sampleJson[0];
  840. }
  841. if(t.nodeName) {
  842. var xmlString = new XMLSerializer().serializeToString(t);
  843. return this.formatXml(xmlString);
  844. }
  845. else
  846. return JSON.stringify(sampleJson, null, 2);
  847. }
  848. else
  849. return sampleJson;
  850. }
  851. };
  852. /**
  853. * legacy binding
  854. **/
  855. Operation.prototype["do"] = function(args, opts, callback, error, parent) {
  856. return this.execute(args, opts, callback, error, parent);
  857. };
  858. /**
  859. * executes an operation
  860. **/
  861. Operation.prototype.execute = function(arg1, arg2, arg3, arg4, parent) {
  862. var args = arg1 || {};
  863. var opts = {}, success, error;
  864. if(typeof arg2 === 'object') {
  865. opts = arg2;
  866. success = arg3;
  867. error = arg4;
  868. }
  869. if(typeof arg2 === 'function') {
  870. success = arg2;
  871. error = arg3;
  872. }
  873. success = (success||log);
  874. error = (error||log);
  875. if(typeof opts.useJQuery === 'boolean') {
  876. this.useJQuery = opts.useJQuery;
  877. }
  878. var missingParams = this.getMissingParams(args);
  879. if(missingParams.length > 0) {
  880. var message = 'missing required params: ' + missingParams;
  881. fail(message);
  882. return;
  883. }
  884. var allHeaders = this.getHeaderParams(args);
  885. var contentTypeHeaders = this.setContentTypes(args, opts);
  886. var headers = {};
  887. for (var attrname in allHeaders) { headers[attrname] = allHeaders[attrname]; }
  888. for (var attrname in contentTypeHeaders) { headers[attrname] = contentTypeHeaders[attrname]; }
  889. var body = this.getBody(headers, args);
  890. var url = this.urlify(args);
  891. var obj = {
  892. url: url,
  893. method: this.method.toUpperCase(),
  894. body: body,
  895. useJQuery: this.useJQuery,
  896. headers: headers,
  897. on: {
  898. response: function(response) {
  899. return success(response, parent);
  900. },
  901. error: function(response) {
  902. return error(response, parent);
  903. }
  904. }
  905. };
  906. var status = e.authorizations.apply(obj, this.operation.security);
  907. if(opts.mock === true)
  908. return obj;
  909. else
  910. new SwaggerHttp().execute(obj);
  911. };
  912. Operation.prototype.setContentTypes = function(args, opts) {
  913. // default type
  914. var accepts = 'application/json';
  915. var consumes = args.parameterContentType || 'application/json';
  916. var allDefinedParams = this.parameters;
  917. var definedFormParams = [];
  918. var definedFileParams = [];
  919. var body;
  920. var headers = {};
  921. // get params from the operation and set them in definedFileParams, definedFormParams, headers
  922. var i;
  923. for(i = 0; i < allDefinedParams.length; i++) {
  924. var param = allDefinedParams[i];
  925. if(param.in === 'formData') {
  926. if(param.type === 'file')
  927. definedFileParams.push(param);
  928. else
  929. definedFormParams.push(param);
  930. }
  931. else if(param.in === 'header' && opts) {
  932. var key = param.name;
  933. var headerValue = opts[param.name];
  934. if(typeof opts[param.name] !== 'undefined')
  935. headers[key] = headerValue;
  936. }
  937. else if(param.in === 'body' && typeof args[param.name] !== 'undefined') {
  938. body = args[param.name];
  939. }
  940. }
  941. // if there's a body, need to set the consumes header via requestContentType
  942. if (body && (this.method === 'post' || this.method === 'put' || this.method === 'patch' || this.method === 'delete')) {
  943. if (opts.requestContentType)
  944. consumes = opts.requestContentType;
  945. } else {
  946. // if any form params, content type must be set
  947. if(definedFormParams.length > 0) {
  948. if(opts.requestContentType) // override if set
  949. consumes = opts.requestContentType;
  950. else if(definedFileParams.length > 0) // if a file, must be multipart/form-data
  951. consumes = 'multipart/form-data';
  952. else // default to x-www-from-urlencoded
  953. consumes = 'application/x-www-form-urlencoded';
  954. }
  955. else if (this.type == 'DELETE')
  956. body = '{}';
  957. else if (this.type != 'DELETE')
  958. consumes = null;
  959. }
  960. if (consumes && this.consumes) {
  961. if (this.consumes.indexOf(consumes) === -1) {
  962. log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.consumes));
  963. }
  964. }
  965. if (opts.responseContentType) {
  966. accepts = opts.responseContentType;
  967. } else {
  968. accepts = 'application/json';
  969. }
  970. if (accepts && this.produces) {
  971. if (this.produces.indexOf(accepts) === -1) {
  972. log('server can\'t produce ' + accepts);
  973. }
  974. }
  975. if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded'))
  976. headers['Content-Type'] = consumes;
  977. if (accepts)
  978. headers.Accept = accepts;
  979. return headers;
  980. };
  981. Operation.prototype.asCurl = function (args) {
  982. var results = [];
  983. var headers = this.getHeaderParams(args);
  984. if (headers) {
  985. var key;
  986. for (key in headers)
  987. results.push("--header \"" + key + ": " + headers[key] + "\"");
  988. }
  989. return "curl " + (results.join(" ")) + " " + this.urlify(args);
  990. };
  991. Operation.prototype.encodePathCollection = function(type, name, value) {
  992. var encoded = '';
  993. var i;
  994. var separator = '';
  995. if(type === 'ssv')
  996. separator = '%20';
  997. else if(type === 'tsv')
  998. separator = '\\t';
  999. else if(type === 'pipes')
  1000. separator = '|';
  1001. else
  1002. separator = ',';
  1003. for(i = 0; i < value.length; i++) {
  1004. if(i === 0)
  1005. encoded = this.encodeQueryParam(value[i]);
  1006. else
  1007. encoded += separator + this.encodeQueryParam(value[i]);
  1008. }
  1009. return encoded;
  1010. };
  1011. Operation.prototype.encodeQueryCollection = function(type, name, value) {
  1012. var encoded = '';
  1013. var i;
  1014. if(type === 'default' || type === 'multi') {
  1015. for(i = 0; i < value.length; i++) {
  1016. if(i > 0) encoded += '&';
  1017. encoded += this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
  1018. }
  1019. }
  1020. else {
  1021. var separator = '';
  1022. if(type === 'csv')
  1023. separator = ',';
  1024. else if(type === 'ssv')
  1025. separator = '%20';
  1026. else if(type === 'tsv')
  1027. separator = '\\t';
  1028. else if(type === 'pipes')
  1029. separator = '|';
  1030. else if(type === 'brackets') {
  1031. for(i = 0; i < value.length; i++) {
  1032. if(i !== 0)
  1033. encoded += '&';
  1034. encoded += this.encodeQueryParam(name) + '[]=' + this.encodeQueryParam(value[i]);
  1035. }
  1036. }
  1037. if(separator !== '') {
  1038. for(i = 0; i < value.length; i++) {
  1039. if(i === 0)
  1040. encoded = this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
  1041. else
  1042. encoded += separator + this.encodeQueryParam(value[i]);
  1043. }
  1044. }
  1045. }
  1046. return encoded;
  1047. };
  1048. Operation.prototype.encodeQueryParam = function(arg) {
  1049. return encodeURIComponent(arg);
  1050. };
  1051. /**
  1052. * TODO revisit, might not want to leave '/'
  1053. **/
  1054. Operation.prototype.encodePathParam = function(pathParam) {
  1055. var encParts, part, parts, i, len;
  1056. pathParam = pathParam.toString();
  1057. if (pathParam.indexOf('/') === -1) {
  1058. return encodeURIComponent(pathParam);
  1059. } else {
  1060. parts = pathParam.split('/');
  1061. encParts = [];
  1062. for (i = 0, len = parts.length; i < len; i++) {
  1063. encParts.push(encodeURIComponent(parts[i]));
  1064. }
  1065. return encParts.join('/');
  1066. }
  1067. };
  1068. var Model = function(name, definition) {
  1069. this.name = name;
  1070. this.definition = definition || {};
  1071. this.properties = [];
  1072. var requiredFields = definition.required || [];
  1073. if(definition.type === 'array') {
  1074. var out = new ArrayModel(definition);
  1075. return out;
  1076. }
  1077. var key;
  1078. var props = definition.properties;
  1079. if(props) {
  1080. for(key in props) {
  1081. var required = false;
  1082. var property = props[key];
  1083. if(requiredFields.indexOf(key) >= 0)
  1084. required = true;
  1085. this.properties.push(new Property(key, property, required));
  1086. }
  1087. }
  1088. };
  1089. Model.prototype.createJSONSample = function(modelsToIgnore) {
  1090. var i, result = {};
  1091. modelsToIgnore = (modelsToIgnore||{});
  1092. modelsToIgnore[this.name] = this;
  1093. for (i = 0; i < this.properties.length; i++) {
  1094. prop = this.properties[i];
  1095. var sample = prop.getSampleValue(modelsToIgnore);
  1096. result[prop.name] = sample;
  1097. }
  1098. delete modelsToIgnore[this.name];
  1099. return result;
  1100. };
  1101. Model.prototype.getSampleValue = function(modelsToIgnore) {
  1102. var i, obj = {};
  1103. for(i = 0; i < this.properties.length; i++ ) {
  1104. var property = this.properties[i];
  1105. obj[property.name] = property.sampleValue(false, modelsToIgnore);
  1106. }
  1107. return obj;
  1108. };
  1109. Model.prototype.getMockSignature = function(modelsToIgnore) {
  1110. var i, prop, propertiesStr = [];
  1111. for (i = 0; i < this.properties.length; i++) {
  1112. prop = this.properties[i];
  1113. propertiesStr.push(prop.toString());
  1114. }
  1115. var strong = '<span class="strong">';
  1116. var stronger = '<span class="stronger">';
  1117. var strongClose = '</span>';
  1118. var classOpen = strong + this.name + ' {' + strongClose;
  1119. var classClose = strong + '}' + strongClose;
  1120. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  1121. if (!modelsToIgnore)
  1122. modelsToIgnore = {};
  1123. modelsToIgnore[this.name] = this;
  1124. for (i = 0; i < this.properties.length; i++) {
  1125. prop = this.properties[i];
  1126. var ref = prop.$ref;
  1127. var model = models[ref];
  1128. if (model && typeof modelsToIgnore[model.name] === 'undefined') {
  1129. returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
  1130. }
  1131. }
  1132. return returnVal;
  1133. };
  1134. var Property = function(name, obj, required) {
  1135. this.schema = obj;
  1136. this.required = required;
  1137. if(obj.$ref)
  1138. this.$ref = simpleRef(obj.$ref);
  1139. else if (obj.type === 'array' && obj.items) {
  1140. if(obj.items.$ref)
  1141. this.$ref = simpleRef(obj.items.$ref);
  1142. else
  1143. obj = obj.items;
  1144. }
  1145. this.name = name;
  1146. this.description = obj.description;
  1147. this.obj = obj;
  1148. this.optional = true;
  1149. this.optional = !required;
  1150. this.default = obj.default || null;
  1151. this.example = obj.example || null;
  1152. this.collectionFormat = obj.collectionFormat || null;
  1153. this.maximum = obj.maximum || null;
  1154. this.exclusiveMaximum = obj.exclusiveMaximum || null;
  1155. this.minimum = obj.minimum || null;
  1156. this.exclusiveMinimum = obj.exclusiveMinimum || null;
  1157. this.maxLength = obj.maxLength || null;
  1158. this.minLength = obj.minLength || null;
  1159. this.pattern = obj.pattern || null;
  1160. this.maxItems = obj.maxItems || null;
  1161. this.minItems = obj.minItems || null;
  1162. this.uniqueItems = obj.uniqueItems || null;
  1163. this['enum'] = obj['enum'] || null;
  1164. this.multipleOf = obj.multipleOf || null;
  1165. };
  1166. Property.prototype.getSampleValue = function (modelsToIgnore) {
  1167. return this.sampleValue(false, modelsToIgnore);
  1168. };
  1169. Property.prototype.isArray = function () {
  1170. var schema = this.schema;
  1171. if(schema.type === 'array')
  1172. return true;
  1173. else
  1174. return false;
  1175. };
  1176. Property.prototype.sampleValue = function(isArray, ignoredModels) {
  1177. isArray = (isArray || this.isArray());
  1178. ignoredModels = (ignoredModels || {});
  1179. var type = getStringSignature(this.obj, true);
  1180. var output;
  1181. if(this.$ref) {
  1182. var refModelName = simpleRef(this.$ref);
  1183. var refModel = models[refModelName];
  1184. if(refModel && typeof ignoredModels[type] === 'undefined') {
  1185. ignoredModels[type] = this;
  1186. output = refModel.getSampleValue(ignoredModels);
  1187. }
  1188. else {
  1189. output = refModelName;
  1190. }
  1191. }
  1192. else if(this.example)
  1193. output = this.example;
  1194. else if(this.default)
  1195. output = this.default;
  1196. else if(type === 'date-time')
  1197. output = new Date().toISOString();
  1198. else if(type === 'date')
  1199. output = new Date().toISOString().split("T")[0];
  1200. else if(type === 'string')
  1201. output = 'string';
  1202. else if(type === 'integer')
  1203. output = 0;
  1204. else if(type === 'long')
  1205. output = 0;
  1206. else if(type === 'float')
  1207. output = 0.0;
  1208. else if(type === 'double')
  1209. output = 0.0;
  1210. else if(type === 'boolean')
  1211. output = true;
  1212. else
  1213. output = {};
  1214. ignoredModels[type] = output;
  1215. if(isArray)
  1216. return [output];
  1217. else
  1218. return output;
  1219. };
  1220. getStringSignature = function(obj, baseComponent) {
  1221. var str = '';
  1222. if(typeof obj.$ref !== 'undefined')
  1223. str += simpleRef(obj.$ref);
  1224. else if(typeof obj.type === 'undefined')
  1225. str += 'object';
  1226. else if(obj.type === 'array') {
  1227. if(baseComponent)
  1228. str += getStringSignature((obj.items || obj.$ref || {}));
  1229. else {
  1230. str += 'Array[';
  1231. str += getStringSignature((obj.items || obj.$ref || {}));
  1232. str += ']';
  1233. }
  1234. }
  1235. else if(obj.type === 'integer' && obj.format === 'int32')
  1236. str += 'integer';
  1237. else if(obj.type === 'integer' && obj.format === 'int64')
  1238. str += 'long';
  1239. else if(obj.type === 'integer' && typeof obj.format === 'undefined')
  1240. str += 'long';
  1241. else if(obj.type === 'string' && obj.format === 'date-time')
  1242. str += 'date-time';
  1243. else if(obj.type === 'string' && obj.format === 'date')
  1244. str += 'date';
  1245. else if(obj.type === 'string' && typeof obj.format === 'undefined')
  1246. str += 'string';
  1247. else if(obj.type === 'number' && obj.format === 'float')
  1248. str += 'float';
  1249. else if(obj.type === 'number' && obj.format === 'double')
  1250. str += 'double';
  1251. else if(obj.type === 'number' && typeof obj.format === 'undefined')
  1252. str += 'double';
  1253. else if(obj.type === 'boolean')
  1254. str += 'boolean';
  1255. else if(obj.$ref)
  1256. str += simpleRef(obj.$ref);
  1257. else
  1258. str += obj.type;
  1259. return str;
  1260. };
  1261. simpleRef = function(name) {
  1262. if(typeof name === 'undefined')
  1263. return null;
  1264. if(name.indexOf("#/definitions/") === 0)
  1265. return name.substring('#/definitions/'.length);
  1266. else
  1267. return name;
  1268. };
  1269. Property.prototype.toString = function() {
  1270. var str = getStringSignature(this.obj);
  1271. if(str !== '') {
  1272. str = '<span class="propName ' + this.required + '">' + this.name + '</span> (<span class="propType">' + str + '</span>';
  1273. if(!this.required)
  1274. str += ', <span class="propOptKey">optional</span>';
  1275. str += ')';
  1276. }
  1277. else
  1278. str = this.name + ' (' + JSON.stringify(this.obj) + ')';
  1279. if(typeof this.description !== 'undefined')
  1280. str += ': ' + this.description;
  1281. if (this['enum']) {
  1282. str += ' = <span class="propVals">[\'' + this['enum'].join('\' or \'') + '\']</span>';
  1283. }
  1284. if (this.descr) {
  1285. str += ': <span class="propDesc">' + this.descr + '</span>';
  1286. }
  1287. var options = '';
  1288. var isArray = this.schema.type === 'array';
  1289. var type;
  1290. if(isArray) {
  1291. if(this.schema.items)
  1292. type = this.schema.items.type;
  1293. else
  1294. type = '';
  1295. }
  1296. else {
  1297. this.schema.type;
  1298. }
  1299. if (this.default)
  1300. options += optionHtml('Default', this.default);
  1301. switch (type) {
  1302. case 'string':
  1303. if (this.minLength)
  1304. options += optionHtml('Min. Length', this.minLength);
  1305. if (this.maxLength)
  1306. options += optionHtml('Max. Length', this.maxLength);
  1307. if (this.pattern)
  1308. options += optionHtml('Reg. Exp.', this.pattern);
  1309. break;
  1310. case 'integer':
  1311. case 'number':
  1312. if (this.minimum)
  1313. options += optionHtml('Min. Value', this.minimum);
  1314. if (this.exclusiveMinimum)
  1315. options += optionHtml('Exclusive Min.', "true");
  1316. if (this.maximum)
  1317. options += optionHtml('Max. Value', this.maximum);
  1318. if (this.exclusiveMaximum)
  1319. options += optionHtml('Exclusive Max.', "true");
  1320. if (this.multipleOf)
  1321. options += optionHtml('Multiple Of', this.multipleOf);
  1322. break;
  1323. }
  1324. if (isArray) {
  1325. if (this.minItems)
  1326. options += optionHtml('Min. Items', this.minItems);
  1327. if (this.maxItems)
  1328. options += optionHtml('Max. Items', this.maxItems);
  1329. if (this.uniqueItems)
  1330. options += optionHtml('Unique Items', "true");
  1331. if (this.collectionFormat)
  1332. options += optionHtml('Coll. Format', this.collectionFormat);
  1333. }
  1334. if (this['enum']) {
  1335. var enumString;
  1336. if (type === 'number' || type === 'integer')
  1337. enumString = this['enum'].join(', ');
  1338. else {
  1339. enumString = '"' + this['enum'].join('", "') + '"';
  1340. }
  1341. options += optionHtml('Enum', enumString);
  1342. }
  1343. if (options.length > 0)
  1344. str = '<span class="propWrap">' + str + '<table class="optionsWrapper"><tr><th colspan="2">' + this.name + '</th></tr>' + options + '</table></span>';
  1345. return str;
  1346. };
  1347. optionHtml = function(label, value) {
  1348. return '<tr><td class="optionName">' + label + ':</td><td>' + value + '</td></tr>';
  1349. }
  1350. typeFromJsonSchema = function(type, format) {
  1351. var str;
  1352. if(type === 'integer' && format === 'int32')
  1353. str = 'integer';
  1354. else if(type === 'integer' && format === 'int64')
  1355. str = 'long';
  1356. else if(type === 'integer' && typeof format === 'undefined')
  1357. str = 'long';
  1358. else if(type === 'string' && format === 'date-time')
  1359. str = 'date-time';
  1360. else if(type === 'string' && format === 'date')
  1361. str = 'date';
  1362. else if(type === 'number' && format === 'float')
  1363. str = 'float';
  1364. else if(type === 'number' && format === 'double')
  1365. str = 'double';
  1366. else if(type === 'number' && typeof format === 'undefined')
  1367. str = 'double';
  1368. else if(type === 'boolean')
  1369. str = 'boolean';
  1370. else if(type === 'string')
  1371. str = 'string';
  1372. return str;
  1373. };
  1374. var sampleModels = {};
  1375. var cookies = {};
  1376. var models = {};
  1377. SwaggerClient.prototype.buildFrom1_2Spec = function (response) {
  1378. if (response.apiVersion != null) {
  1379. this.apiVersion = response.apiVersion;
  1380. }
  1381. this.apis = {};
  1382. this.apisArray = [];
  1383. this.consumes = response.consumes;
  1384. this.produces = response.produces;
  1385. this.authSchemes = response.authorizations;
  1386. this.info = this.convertInfo(response.info);
  1387. var isApi = false, i, res;
  1388. for (i = 0; i < response.apis.length; i++) {
  1389. var api = response.apis[i];
  1390. if (api.operations) {
  1391. var j;
  1392. for (j = 0; j < api.operations.length; j++) {
  1393. operation = api.operations[j];
  1394. isApi = true;
  1395. }
  1396. }
  1397. }
  1398. if (response.basePath)
  1399. this.basePath = response.basePath;
  1400. else if (this.url.indexOf('?') > 0)
  1401. this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
  1402. else
  1403. this.basePath = this.url;
  1404. if (isApi) {
  1405. var newName = response.resourcePath.replace(/\//g, '');
  1406. this.resourcePath = response.resourcePath;
  1407. res = new SwaggerResource(response, this);
  1408. this.apis[newName] = res;
  1409. this.apisArray.push(res);
  1410. } else {
  1411. var k;
  1412. for (k = 0; k < response.apis.length; k++) {
  1413. var resource = response.apis[k];
  1414. res = new SwaggerResource(resource, this);
  1415. this.apis[res.name] = res;
  1416. this.apisArray.push(res);
  1417. }
  1418. }
  1419. this.isValid = true;
  1420. if (typeof this.success === 'function') {
  1421. this.success();
  1422. }
  1423. return this;
  1424. };
  1425. SwaggerClient.prototype.buildFrom1_1Spec = function (response) {
  1426. log('This API is using a deprecated version of Swagger! Please see http://github.com/wordnik/swagger-core/wiki for more info');
  1427. if (response.apiVersion != null)
  1428. this.apiVersion = response.apiVersion;
  1429. this.apis = {};
  1430. this.apisArray = [];
  1431. this.produces = response.produces;
  1432. this.info = this.convertInfo(response.info);
  1433. var isApi = false, res;
  1434. for (var i = 0; i < response.apis.length; i++) {
  1435. var api = response.apis[i];
  1436. if (api.operations) {
  1437. for (var j = 0; j < api.operations.length; j++) {
  1438. operation = api.operations[j];
  1439. isApi = true;
  1440. }
  1441. }
  1442. }
  1443. if (response.basePath) {
  1444. this.basePath = response.basePath;
  1445. } else if (this.url.indexOf('?') > 0) {
  1446. this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
  1447. } else {
  1448. this.basePath = this.url;
  1449. }
  1450. if (isApi) {
  1451. var newName = response.resourcePath.replace(/\//g, '');
  1452. this.resourcePath = response.resourcePath;
  1453. res = new SwaggerResource(response, this);
  1454. this.apis[newName] = res;
  1455. this.apisArray.push(res);
  1456. } else {
  1457. for (k = 0; k < response.apis.length; k++) {
  1458. resource = response.apis[k];
  1459. res = new SwaggerResource(resource, this);
  1460. this.apis[res.name] = res;
  1461. this.apisArray.push(res);
  1462. }
  1463. }
  1464. this.isValid = true;
  1465. if (this.success) {
  1466. this.success();
  1467. }
  1468. return this;
  1469. };
  1470. SwaggerClient.prototype.convertInfo = function (resp) {
  1471. if(typeof resp == 'object') {
  1472. var info = {}
  1473. info.title = resp.title;
  1474. info.description = resp.description;
  1475. info.termsOfService = resp.termsOfServiceUrl;
  1476. info.contact = {};
  1477. info.contact.name = resp.contact;
  1478. info.license = {};
  1479. info.license.name = resp.license;
  1480. info.license.url = resp.licenseUrl;
  1481. return info;
  1482. }
  1483. };
  1484. SwaggerClient.prototype.selfReflect = function () {
  1485. var resource, resource_name, ref;
  1486. if (this.apis === null) {
  1487. return false;
  1488. }
  1489. ref = this.apis;
  1490. for (resource_name in ref) {
  1491. resource = ref[resource_name];
  1492. if (resource.ready === null) {
  1493. return false;
  1494. }
  1495. }
  1496. this.setConsolidatedModels();
  1497. this.ready = true;
  1498. if (typeof this.success === 'function') {
  1499. return this.success();
  1500. }
  1501. };
  1502. SwaggerClient.prototype.setConsolidatedModels = function () {
  1503. var model, modelName, resource, resource_name, i, apis, models, results;
  1504. this.models = {};
  1505. apis = this.apis;
  1506. for (resource_name in apis) {
  1507. resource = apis[resource_name];
  1508. for (modelName in resource.models) {
  1509. if (typeof this.models[modelName] === 'undefined') {
  1510. this.models[modelName] = resource.models[modelName];
  1511. this.modelsArray.push(resource.models[modelName]);
  1512. }
  1513. }
  1514. }
  1515. models = this.modelsArray;
  1516. results = [];
  1517. for (i = 0; i < models.length; i++) {
  1518. model = models[i];
  1519. results.push(model.setReferencedModels(this.models));
  1520. }
  1521. return results;
  1522. };
  1523. var SwaggerResource = function (resourceObj, api) {
  1524. var _this = this;
  1525. this.api = api;
  1526. this.swaggerRequstHeaders = api.swaggerRequstHeaders;
  1527. this.path = (typeof this.api.resourcePath === 'string') ? this.api.resourcePath : resourceObj.path;
  1528. this.description = resourceObj.description;
  1529. this.authorizations = (resourceObj.authorizations || {});
  1530. var parts = this.path.split('/');
  1531. this.name = parts[parts.length - 1].replace('.{format}', '');
  1532. this.basePath = this.api.basePath;
  1533. this.operations = {};
  1534. this.operationsArray = [];
  1535. this.modelsArray = [];
  1536. this.models = {};
  1537. this.rawModels = {};
  1538. this.useJQuery = (typeof api.useJQuery !== 'undefined') ? api.useJQuery : null;
  1539. if ((resourceObj.apis) && this.api.resourcePath) {
  1540. this.addApiDeclaration(resourceObj);
  1541. } else {
  1542. if (typeof this.path === 'undefined') {
  1543. this.api.fail('SwaggerResources must have a path.');
  1544. }
  1545. if (this.path.substring(0, 4) === 'http') {
  1546. this.url = this.path.replace('{format}', 'json');
  1547. } else {
  1548. this.url = this.api.basePath + this.path.replace('{format}', 'json');
  1549. }
  1550. this.api.progress('fetching resource ' + this.name + ': ' + this.url);
  1551. var obj = {
  1552. url: this.url,
  1553. method: 'GET',
  1554. useJQuery: this.useJQuery,
  1555. headers: {
  1556. accept: this.swaggerRequstHeaders
  1557. },
  1558. on: {
  1559. response: function (resp) {
  1560. var responseObj = resp.obj || JSON.parse(resp.data);
  1561. return _this.addApiDeclaration(responseObj);
  1562. },
  1563. error: function (response) {
  1564. return _this.api.fail('Unable to read api \'' +
  1565. _this.name + '\' from path ' + _this.url + ' (server returned ' + response.statusText + ')');
  1566. }
  1567. }
  1568. };
  1569. var e = typeof window !== 'undefined' ? window : exports;
  1570. e.authorizations.apply(obj);
  1571. new SwaggerHttp().execute(obj);
  1572. }
  1573. };
  1574. SwaggerResource.prototype.getAbsoluteBasePath = function (relativeBasePath) {
  1575. var pos, url;
  1576. url = this.api.basePath;
  1577. pos = url.lastIndexOf(relativeBasePath);
  1578. var parts = url.split('/');
  1579. var rootUrl = parts[0] + '//' + parts[2];
  1580. if (relativeBasePath.indexOf('http') === 0)
  1581. return relativeBasePath;
  1582. if (relativeBasePath === '/')
  1583. return rootUrl;
  1584. if (relativeBasePath.substring(0, 1) == '/') {
  1585. // use root + relative
  1586. return rootUrl + relativeBasePath;
  1587. }
  1588. else {
  1589. pos = this.basePath.lastIndexOf('/');
  1590. var base = this.basePath.substring(0, pos);
  1591. if (base.substring(base.length - 1) == '/')
  1592. return base + relativeBasePath;
  1593. else
  1594. return base + '/' + relativeBasePath;
  1595. }
  1596. };
  1597. SwaggerResource.prototype.addApiDeclaration = function (response) {
  1598. if (typeof response.produces === 'string')
  1599. this.produces = response.produces;
  1600. if (typeof response.consumes === 'string')
  1601. this.consumes = response.consumes;
  1602. if ((typeof response.basePath === 'string') && response.basePath.replace(/\s/g, '').length > 0)
  1603. this.basePath = response.basePath.indexOf('http') === -1 ? this.getAbsoluteBasePath(response.basePath) : response.basePath;
  1604. this.addModels(response.models);
  1605. if (response.apis) {
  1606. for (var i = 0 ; i < response.apis.length; i++) {
  1607. var endpoint = response.apis[i];
  1608. this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces);
  1609. }
  1610. }
  1611. this.api[this.name] = this;
  1612. this.ready = true;
  1613. return this.api.selfReflect();
  1614. };
  1615. SwaggerResource.prototype.addModels = function (models) {
  1616. if (typeof models === 'object') {
  1617. var modelName;
  1618. for (modelName in models) {
  1619. if (typeof this.models[modelName] === 'undefined') {
  1620. var swaggerModel = new SwaggerModel(modelName, models[modelName]);
  1621. this.modelsArray.push(swaggerModel);
  1622. this.models[modelName] = swaggerModel;
  1623. this.rawModels[modelName] = models[modelName];
  1624. }
  1625. }
  1626. var output = [];
  1627. for (var i = 0; i < this.modelsArray.length; i++) {
  1628. var model = this.modelsArray[i];
  1629. output.push(model.setReferencedModels(this.models));
  1630. }
  1631. return output;
  1632. }
  1633. };
  1634. SwaggerResource.prototype.addOperations = function (resource_path, ops, consumes, produces) {
  1635. if (ops) {
  1636. var output = [];
  1637. for (var i = 0; i < ops.length; i++) {
  1638. var o = ops[i];
  1639. consumes = this.consumes;
  1640. produces = this.produces;
  1641. if (typeof o.consumes !== 'undefined')
  1642. consumes = o.consumes;
  1643. else
  1644. consumes = this.consumes;
  1645. if (typeof o.produces !== 'undefined')
  1646. produces = o.produces;
  1647. else
  1648. produces = this.produces;
  1649. var type = (o.type || o.responseClass);
  1650. if (type === 'array') {
  1651. ref = null;
  1652. if (o.items)
  1653. ref = o.items.type || o.items.$ref;
  1654. type = 'array[' + ref + ']';
  1655. }
  1656. var responseMessages = o.responseMessages;
  1657. var method = o.method;
  1658. if (o.httpMethod) {
  1659. method = o.httpMethod;
  1660. }
  1661. if (o.supportedContentTypes) {
  1662. consumes = o.supportedContentTypes;
  1663. }
  1664. if (o.errorResponses) {
  1665. responseMessages = o.errorResponses;
  1666. for (var j = 0; j < responseMessages.length; j++) {
  1667. r = responseMessages[j];
  1668. r.message = r.reason;
  1669. r.reason = null;
  1670. }
  1671. }
  1672. o.nickname = this.sanitize(o.nickname);
  1673. var op = new SwaggerOperation(o.nickname,
  1674. resource_path,
  1675. method,
  1676. o.parameters,
  1677. o.summary,
  1678. o.notes,
  1679. type,
  1680. responseMessages,
  1681. this,
  1682. consumes,
  1683. produces,
  1684. o.authorizations,
  1685. o.deprecated);
  1686. this.operations[op.nickname] = op;
  1687. output.push(this.operationsArray.push(op));
  1688. }
  1689. return output;
  1690. }
  1691. };
  1692. SwaggerResource.prototype.sanitize = function (nickname) {
  1693. var op;
  1694. op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|.\/?,\\'""-]/g, '_');
  1695. op = op.replace(/((_){2,})/g, '_');
  1696. op = op.replace(/^(_)*/g, '');
  1697. op = op.replace(/([_])*$/g, '');
  1698. return op;
  1699. };
  1700. var SwaggerModel = function (modelName, obj) {
  1701. this.name = typeof obj.id !== 'undefined' ? obj.id : modelName;
  1702. this.properties = [];
  1703. var propertyName;
  1704. for (propertyName in obj.properties) {
  1705. if (obj.required) {
  1706. var value;
  1707. for (value in obj.required) {
  1708. if (propertyName === obj.required[value]) {
  1709. obj.properties[propertyName].required = true;
  1710. }
  1711. }
  1712. }
  1713. var prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName], this);
  1714. this.properties.push(prop);
  1715. }
  1716. };
  1717. SwaggerModel.prototype.setReferencedModels = function (allModels) {
  1718. var results = [];
  1719. for (var i = 0; i < this.properties.length; i++) {
  1720. var property = this.properties[i];
  1721. var type = property.type || property.dataType;
  1722. if (allModels[type])
  1723. results.push(property.refModel = allModels[type]);
  1724. else if ((property.refDataType) && (allModels[property.refDataType]))
  1725. results.push(property.refModel = allModels[property.refDataType]);
  1726. else
  1727. results.push(void 0);
  1728. }
  1729. return results;
  1730. };
  1731. SwaggerModel.prototype.getMockSignature = function (modelsToIgnore) {
  1732. var i, prop, propertiesStr = [];
  1733. for (i = 0; i < this.properties.length; i++) {
  1734. prop = this.properties[i];
  1735. propertiesStr.push(prop.toString());
  1736. }
  1737. var strong = '<span class="strong">';
  1738. var strongClose = '</span>';
  1739. var classOpen = strong + this.name + ' {' + strongClose;
  1740. var classClose = strong + '}' + strongClose;
  1741. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  1742. if (!modelsToIgnore)
  1743. modelsToIgnore = [];
  1744. modelsToIgnore.push(this.name);
  1745. for (i = 0; i < this.properties.length; i++) {
  1746. prop = this.properties[i];
  1747. if ((prop.refModel) && modelsToIgnore.indexOf(prop.refModel.name) === -1) {
  1748. returnVal = returnVal + ('<br>' + prop.refModel.getMockSignature(modelsToIgnore));
  1749. }
  1750. }
  1751. return returnVal;
  1752. };
  1753. SwaggerModel.prototype.createJSONSample = function (modelsToIgnore) {
  1754. if (sampleModels[this.name]) {
  1755. return sampleModels[this.name];
  1756. }
  1757. else {
  1758. var result = {};
  1759. modelsToIgnore = (modelsToIgnore || []);
  1760. modelsToIgnore.push(this.name);
  1761. for (var i = 0; i < this.properties.length; i++) {
  1762. var prop = this.properties[i];
  1763. result[prop.name] = prop.getSampleValue(modelsToIgnore);
  1764. }
  1765. modelsToIgnore.pop(this.name);
  1766. return result;
  1767. }
  1768. };
  1769. var SwaggerModelProperty = function (name, obj, model) {
  1770. this.name = name;
  1771. this.dataType = obj.type || obj.dataType || obj.$ref;
  1772. this.isCollection = this.dataType && (this.dataType.toLowerCase() === 'array' || this.dataType.toLowerCase() === 'list' || this.dataType.toLowerCase() === 'set');
  1773. this.descr = obj.description;
  1774. this.required = obj.required;
  1775. this.defaultValue = applyModelPropertyMacro(obj, model);
  1776. if (obj.items) {
  1777. if (obj.items.type) {
  1778. this.refDataType = obj.items.type;
  1779. }
  1780. if (obj.items.$ref) {
  1781. this.refDataType = obj.items.$ref;
  1782. }
  1783. }
  1784. this.dataTypeWithRef = this.refDataType ? (this.dataType + '[' + this.refDataType + ']') : this.dataType;
  1785. if (obj.allowableValues) {
  1786. this.valueType = obj.allowableValues.valueType;
  1787. this.values = obj.allowableValues.values;
  1788. if (this.values) {
  1789. this.valuesString = '\'' + this.values.join('\' or \'') + '\'';
  1790. }
  1791. }
  1792. if (obj['enum']) {
  1793. this.valueType = 'string';
  1794. this.values = obj['enum'];
  1795. if (this.values) {
  1796. this.valueString = '\'' + this.values.join('\' or \'') + '\'';
  1797. }
  1798. }
  1799. };
  1800. SwaggerModelProperty.prototype.getSampleValue = function (modelsToIgnore) {
  1801. var result;
  1802. if ((this.refModel) && (modelsToIgnore.indexOf(this.refModel.name) === -1)) {
  1803. result = this.refModel.createJSONSample(modelsToIgnore);
  1804. } else {
  1805. if (this.isCollection) {
  1806. result = this.toSampleValue(this.refDataType);
  1807. } else {
  1808. result = this.toSampleValue(this.dataType);
  1809. }
  1810. }
  1811. if (this.isCollection) {
  1812. return [result];
  1813. } else {
  1814. return result;
  1815. }
  1816. };
  1817. SwaggerModelProperty.prototype.toSampleValue = function (value) {
  1818. var result;
  1819. if ((typeof this.defaultValue !== 'undefined') && this.defaultValue) {
  1820. result = this.defaultValue;
  1821. } else if (value === 'integer') {
  1822. result = 0;
  1823. } else if (value === 'boolean') {
  1824. result = false;
  1825. } else if (value === 'double' || value === 'number') {
  1826. result = 0.0;
  1827. } else if (value === 'string') {
  1828. result = '';
  1829. } else {
  1830. result = value;
  1831. }
  1832. return result;
  1833. };
  1834. SwaggerModelProperty.prototype.toString = function () {
  1835. var req = this.required ? 'propReq' : 'propOpt';
  1836. var str = '<span class="propName ' + req + '">' + this.name + '</span> (<span class="propType">' + this.dataTypeWithRef + '</span>';
  1837. if (!this.required) {
  1838. str += ', <span class="propOptKey">optional</span>';
  1839. }
  1840. str += ')';
  1841. if (this.values) {
  1842. str += ' = <span class="propVals">[\'' + this.values.join('\' or \'') + '\']</span>';
  1843. }
  1844. if (this.descr) {
  1845. str += ': <span class="propDesc">' + this.descr + '</span>';
  1846. }
  1847. return str;
  1848. };
  1849. var SwaggerOperation = function (nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations, deprecated) {
  1850. var _this = this;
  1851. var errors = [];
  1852. this.nickname = (nickname || errors.push('SwaggerOperations must have a nickname.'));
  1853. this.path = (path || errors.push('SwaggerOperation ' + nickname + ' is missing path.'));
  1854. this.method = (method || errors.push('SwaggerOperation ' + nickname + ' is missing method.'));
  1855. this.parameters = parameters ? parameters : [];
  1856. this.summary = summary;
  1857. this.notes = notes;
  1858. this.type = type;
  1859. this.responseMessages = (responseMessages || []);
  1860. this.resource = (resource || errors.push('Resource is required'));
  1861. this.consumes = consumes;
  1862. this.produces = produces;
  1863. this.authorizations = typeof authorizations !== 'undefined' ? authorizations : resource.authorizations;
  1864. this.deprecated = (typeof deprecated === 'string' ? Boolean(deprecated) : deprecated);
  1865. this['do'] = __bind(this['do'], this);
  1866. if (errors.length > 0) {
  1867. console.error('SwaggerOperation errors', errors, arguments);
  1868. this.resource.api.fail(errors);
  1869. }
  1870. this.path = this.path.replace('{format}', 'json');
  1871. this.method = this.method.toLowerCase();
  1872. this.isGetMethod = this.method === 'GET';
  1873. var i, j, v;
  1874. this.resourceName = this.resource.name;
  1875. if (typeof this.type !== 'undefined' && this.type === 'void')
  1876. this.type = null;
  1877. else {
  1878. this.responseClassSignature = this.getSignature(this.type, this.resource.models);
  1879. this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models);
  1880. }
  1881. for (i = 0; i < this.parameters.length; i++) {
  1882. var param = this.parameters[i];
  1883. // might take this away
  1884. param.name = param.name || param.type || param.dataType;
  1885. // for 1.1 compatibility
  1886. type = param.type || param.dataType;
  1887. if (type === 'array') {
  1888. type = 'array[' + (param.items.$ref ? param.items.$ref : param.items.type) + ']';
  1889. }
  1890. param.type = type;
  1891. if (type && type.toLowerCase() === 'boolean') {
  1892. param.allowableValues = {};
  1893. param.allowableValues.values = ['true', 'false'];
  1894. }
  1895. param.signature = this.getSignature(type, this.resource.models);
  1896. param.sampleJSON = this.getSampleJSON(type, this.resource.models);
  1897. var enumValue = param['enum'];
  1898. if (typeof enumValue !== 'undefined') {
  1899. param.isList = true;
  1900. param.allowableValues = {};
  1901. param.allowableValues.descriptiveValues = [];
  1902. for (j = 0; j < enumValue.length; j++) {
  1903. v = enumValue[j];
  1904. if (param.defaultValue) {
  1905. param.allowableValues.descriptiveValues.push({
  1906. value: String(v),
  1907. isDefault: (v === param.defaultValue)
  1908. });
  1909. }
  1910. else {
  1911. param.allowableValues.descriptiveValues.push({
  1912. value: String(v),
  1913. isDefault: false
  1914. });
  1915. }
  1916. }
  1917. }
  1918. else if (param.allowableValues != null) {
  1919. if (param.allowableValues.valueType === 'RANGE')
  1920. param.isRange = true;
  1921. else
  1922. param.isList = true;
  1923. if (param.allowableValues != null) {
  1924. param.allowableValues.descriptiveValues = [];
  1925. if (param.allowableValues.values) {
  1926. for (j = 0; j < param.allowableValues.values.length; j++) {
  1927. v = param.allowableValues.values[j];
  1928. if (param.defaultValue != null) {
  1929. param.allowableValues.descriptiveValues.push({
  1930. value: String(v),
  1931. isDefault: (v === param.defaultValue)
  1932. });
  1933. }
  1934. else {
  1935. param.allowableValues.descriptiveValues.push({
  1936. value: String(v),
  1937. isDefault: false
  1938. });
  1939. }
  1940. }
  1941. }
  1942. }
  1943. }
  1944. param.defaultValue = applyParameterMacro(this, param);
  1945. }
  1946. var defaultSuccessCallback = this.resource.api.defaultSuccessCallback || null;
  1947. var defaultErrorCallback = this.resource.api.defaultErrorCallback || null;
  1948. this.resource[this.nickname] = function (args, opts, callback, error) {
  1949. var arg1, arg2, arg3, arg4;
  1950. if(typeof args === 'function') { // right shift 3
  1951. arg1 = {}; arg2 = {}; arg3 = args; arg4 = opts;
  1952. }
  1953. else if(typeof args === 'object' && typeof opts === 'function') { // right shift 2
  1954. arg1 = args; arg2 = {}; arg3 = opts; arg4 = callback;
  1955. }
  1956. else {
  1957. arg1 = args; arg2 = opts; arg3 = callback; arg4 = error;
  1958. }
  1959. return _this['do'](arg1 || {}, arg2 || {}, arg3 || defaultSuccessCallback, arg4 || defaultErrorCallback);
  1960. };
  1961. this.resource[this.nickname].help = function () {
  1962. return _this.help();
  1963. };
  1964. this.resource[this.nickname].asCurl = function (args) {
  1965. return _this.asCurl(args);
  1966. };
  1967. };
  1968. SwaggerOperation.prototype.isListType = function (type) {
  1969. if (type && type.indexOf('[') >= 0) {
  1970. return type.substring(type.indexOf('[') + 1, type.indexOf(']'));
  1971. } else {
  1972. return void 0;
  1973. }
  1974. };
  1975. SwaggerOperation.prototype.getSignature = function (type, models) {
  1976. var isPrimitive, listType;
  1977. listType = this.isListType(type);
  1978. isPrimitive = ((typeof listType !== 'undefined') && models[listType]) || (typeof models[type] !== 'undefined') ? false : true;
  1979. if (isPrimitive) {
  1980. return type;
  1981. } else {
  1982. if (typeof listType !== 'undefined') {
  1983. return models[listType].getMockSignature();
  1984. } else {
  1985. return models[type].getMockSignature();
  1986. }
  1987. }
  1988. };
  1989. SwaggerOperation.prototype.getSampleJSON = function (type, models) {
  1990. var isPrimitive, listType, val;
  1991. listType = this.isListType(type);
  1992. isPrimitive = ((typeof listType !== 'undefined') && models[listType]) || (typeof models[type] !== 'undefined') ? false : true;
  1993. val = isPrimitive ? void 0 : (listType != null ? models[listType].createJSONSample() : models[type].createJSONSample());
  1994. if (val) {
  1995. val = listType ? [val] : val;
  1996. if (typeof val == 'string')
  1997. return val;
  1998. else if (typeof val === 'object') {
  1999. var t = val;
  2000. if (val instanceof Array && val.length > 0) {
  2001. t = val[0];
  2002. }
  2003. if (t.nodeName) {
  2004. var xmlString = new XMLSerializer().serializeToString(t);
  2005. return this.formatXml(xmlString);
  2006. }
  2007. else
  2008. return JSON.stringify(val, null, 2);
  2009. }
  2010. else
  2011. return val;
  2012. }
  2013. };
  2014. SwaggerOperation.prototype['do'] = function (args, opts, callback, error) {
  2015. var key, param, params, possibleParams = [], req, value;
  2016. if (typeof error !== 'function') {
  2017. error = function (xhr, textStatus, error) {
  2018. return log(xhr, textStatus, error);
  2019. };
  2020. }
  2021. if (typeof callback !== 'function') {
  2022. callback = function (response) {
  2023. var content;
  2024. content = null;
  2025. if (response != null) {
  2026. content = response.data;
  2027. } else {
  2028. content = 'no data';
  2029. }
  2030. return log('default callback: ' + content);
  2031. };
  2032. }
  2033. params = {};
  2034. params.headers = [];
  2035. if (args.headers != null) {
  2036. params.headers = args.headers;
  2037. delete args.headers;
  2038. }
  2039. // allow override from the opts
  2040. if(opts && opts.responseContentType) {
  2041. params.headers['Content-Type'] = opts.responseContentType;
  2042. }
  2043. if(opts && opts.requestContentType) {
  2044. params.headers.Accept = opts.requestContentType;
  2045. }
  2046. for (var i = 0; i < this.parameters.length; i++) {
  2047. param = this.parameters[i];
  2048. if (param.paramType === 'header') {
  2049. if (typeof args[param.name] !== 'undefined')
  2050. params.headers[param.name] = args[param.name];
  2051. }
  2052. else if (param.paramType === 'form' || param.paramType.toLowerCase() === 'file')
  2053. possibleParams.push(param);
  2054. else if (param.paramType === 'body' && param.name !== 'body' && typeof args[param.name] !== 'undefined') {
  2055. if (args.body) {
  2056. throw new Error('Saw two body params in an API listing; expecting a max of one.');
  2057. }
  2058. args.body = args[param.name];
  2059. }
  2060. }
  2061. if (typeof args.body !== 'undefined') {
  2062. params.body = args.body;
  2063. delete args.body;
  2064. }
  2065. if (possibleParams) {
  2066. for (key in possibleParams) {
  2067. value = possibleParams[key];
  2068. if (args[value.name]) {
  2069. params[value.name] = args[value.name];
  2070. }
  2071. }
  2072. }
  2073. req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this);
  2074. if (opts.mock) {
  2075. return req;
  2076. } else {
  2077. return true;
  2078. }
  2079. };
  2080. SwaggerOperation.prototype.pathJson = function () {
  2081. return this.path.replace('{format}', 'json');
  2082. };
  2083. SwaggerOperation.prototype.pathXml = function () {
  2084. return this.path.replace('{format}', 'xml');
  2085. };
  2086. SwaggerOperation.prototype.encodePathParam = function (pathParam) {
  2087. var encParts, part, parts, _i, _len;
  2088. pathParam = pathParam.toString();
  2089. if (pathParam.indexOf('/') === -1) {
  2090. return encodeURIComponent(pathParam);
  2091. } else {
  2092. parts = pathParam.split('/');
  2093. encParts = [];
  2094. for (_i = 0, _len = parts.length; _i < _len; _i++) {
  2095. part = parts[_i];
  2096. encParts.push(encodeURIComponent(part));
  2097. }
  2098. return encParts.join('/');
  2099. }
  2100. };
  2101. SwaggerOperation.prototype.urlify = function (args) {
  2102. var i, j, param, url;
  2103. // ensure no double slashing...
  2104. if(this.resource.basePath.length > 1 && this.resource.basePath.slice(-1) === '/' && this.pathJson().charAt(0) === '/')
  2105. url = this.resource.basePath + this.pathJson().substring(1);
  2106. else
  2107. url = this.resource.basePath + this.pathJson();
  2108. var params = this.parameters;
  2109. for (i = 0; i < params.length; i++) {
  2110. param = params[i];
  2111. if (param.paramType === 'path') {
  2112. if (typeof args[param.name] !== 'undefined') {
  2113. // apply path params and remove from args
  2114. var reg = new RegExp('\\{\\s*?' + param.name + '.*?\\}(?=\\s*?(\\/?|$))', 'gi');
  2115. url = url.replace(reg, this.encodePathParam(args[param.name]));
  2116. delete args[param.name];
  2117. }
  2118. else
  2119. throw '' + param.name + ' is a required path param.';
  2120. }
  2121. }
  2122. var queryParams = '';
  2123. for (i = 0; i < params.length; i++) {
  2124. param = params[i];
  2125. if(param.paramType === 'query') {
  2126. if (queryParams !== '')
  2127. queryParams += '&';
  2128. if (Array.isArray(param)) {
  2129. var output = '';
  2130. for(j = 0; j < param.length; j++) {
  2131. if(j > 0)
  2132. output += ',';
  2133. output += encodeURIComponent(param[j]);
  2134. }
  2135. queryParams += encodeURIComponent(param.name) + '=' + output;
  2136. }
  2137. else {
  2138. if (typeof args[param.name] !== 'undefined') {
  2139. queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]);
  2140. } else {
  2141. if (param.required)
  2142. throw '' + param.name + ' is a required query param.';
  2143. }
  2144. }
  2145. }
  2146. }
  2147. if ((queryParams != null) && queryParams.length > 0)
  2148. url += '?' + queryParams;
  2149. return url;
  2150. };
  2151. SwaggerOperation.prototype.supportHeaderParams = function () {
  2152. return this.resource.api.supportHeaderParams;
  2153. };
  2154. SwaggerOperation.prototype.supportedSubmitMethods = function () {
  2155. return this.resource.api.supportedSubmitMethods;
  2156. };
  2157. SwaggerOperation.prototype.getQueryParams = function (args) {
  2158. return this.getMatchingParams(['query'], args);
  2159. };
  2160. SwaggerOperation.prototype.getHeaderParams = function (args) {
  2161. return this.getMatchingParams(['header'], args);
  2162. };
  2163. SwaggerOperation.prototype.getMatchingParams = function (paramTypes, args) {
  2164. var matchingParams = {};
  2165. var params = this.parameters;
  2166. for (var i = 0; i < params.length; i++) {
  2167. param = params[i];
  2168. if (args && args[param.name])
  2169. matchingParams[param.name] = args[param.name];
  2170. }
  2171. var headers = this.resource.api.headers;
  2172. var name;
  2173. for (name in headers) {
  2174. var value = headers[name];
  2175. matchingParams[name] = value;
  2176. }
  2177. return matchingParams;
  2178. };
  2179. SwaggerOperation.prototype.help = function () {
  2180. var msg = '';
  2181. var params = this.parameters;
  2182. for (var i = 0; i < params.length; i++) {
  2183. var param = params[i];
  2184. if (msg !== '')
  2185. msg += '\n';
  2186. msg += '* ' + param.name + (param.required ? ' (required)' : '') + " - " + param.description;
  2187. }
  2188. return msg;
  2189. };
  2190. SwaggerOperation.prototype.asCurl = function (args) {
  2191. var results = [];
  2192. var i;
  2193. var headers = SwaggerRequest.prototype.setHeaders(args, {}, this);
  2194. for(i = 0; i < this.parameters.length; i++) {
  2195. var param = this.parameters[i];
  2196. if(param.paramType && param.paramType === 'header' && args[param.name]) {
  2197. headers[param.name] = args[param.name];
  2198. }
  2199. }
  2200. var key;
  2201. for (key in headers) {
  2202. results.push('--header "' + key + ': ' + headers[key] + '"');
  2203. }
  2204. return 'curl ' + (results.join(' ')) + ' ' + this.urlify(args);
  2205. };
  2206. SwaggerOperation.prototype.formatXml = function (xml) {
  2207. var contexp, formatted, indent, lastType, lines, ln, pad, reg, transitions, wsexp, _fn, _i, _len;
  2208. reg = /(>)(<)(\/*)/g;
  2209. wsexp = /[ ]*(.*)[ ]+\n/g;
  2210. contexp = /(<.+>)(.+\n)/g;
  2211. xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
  2212. pad = 0;
  2213. formatted = '';
  2214. lines = xml.split('\n');
  2215. indent = 0;
  2216. lastType = 'other';
  2217. transitions = {
  2218. 'single->single': 0,
  2219. 'single->closing': -1,
  2220. 'single->opening': 0,
  2221. 'single->other': 0,
  2222. 'closing->single': 0,
  2223. 'closing->closing': -1,
  2224. 'closing->opening': 0,
  2225. 'closing->other': 0,
  2226. 'opening->single': 1,
  2227. 'opening->closing': 0,
  2228. 'opening->opening': 1,
  2229. 'opening->other': 1,
  2230. 'other->single': 0,
  2231. 'other->closing': -1,
  2232. 'other->opening': 0,
  2233. 'other->other': 0
  2234. };
  2235. _fn = function (ln) {
  2236. var fromTo, j, key, padding, type, types, value;
  2237. types = {
  2238. single: Boolean(ln.match(/<.+\/>/)),
  2239. closing: Boolean(ln.match(/<\/.+>/)),
  2240. opening: Boolean(ln.match(/<[^!?].*>/))
  2241. };
  2242. type = ((function () {
  2243. var _results;
  2244. _results = [];
  2245. for (key in types) {
  2246. value = types[key];
  2247. if (value) {
  2248. _results.push(key);
  2249. }
  2250. }
  2251. return _results;
  2252. })())[0];
  2253. type = type === void 0 ? 'other' : type;
  2254. fromTo = lastType + '->' + type;
  2255. lastType = type;
  2256. padding = '';
  2257. indent += transitions[fromTo];
  2258. padding = ((function () {
  2259. var _j, _ref5, _results;
  2260. _results = [];
  2261. for (j = _j = 0, _ref5 = indent; 0 <= _ref5 ? _j < _ref5 : _j > _ref5; j = 0 <= _ref5 ? ++_j : --_j) {
  2262. _results.push(' ');
  2263. }
  2264. return _results;
  2265. })()).join('');
  2266. if (fromTo === 'opening->closing') {
  2267. formatted = formatted.substr(0, formatted.length - 1) + ln + '\n';
  2268. } else {
  2269. formatted += padding + ln + '\n';
  2270. }
  2271. };
  2272. for (_i = 0, _len = lines.length; _i < _len; _i++) {
  2273. ln = lines[_i];
  2274. _fn(ln);
  2275. }
  2276. return formatted;
  2277. };
  2278. var SwaggerRequest = function (type, url, params, opts, successCallback, errorCallback, operation, execution) {
  2279. var _this = this;
  2280. var errors = [];
  2281. this.useJQuery = (typeof operation.resource.useJQuery !== 'undefined' ? operation.resource.useJQuery : null);
  2282. this.type = (type || errors.push('SwaggerRequest type is required (get/post/put/delete/patch/options).'));
  2283. this.url = (url || errors.push('SwaggerRequest url is required.'));
  2284. this.params = params;
  2285. this.opts = opts;
  2286. this.successCallback = (successCallback || errors.push('SwaggerRequest successCallback is required.'));
  2287. this.errorCallback = (errorCallback || errors.push('SwaggerRequest error callback is required.'));
  2288. this.operation = (operation || errors.push('SwaggerRequest operation is required.'));
  2289. this.execution = execution;
  2290. this.headers = (params.headers || {});
  2291. if (errors.length > 0) {
  2292. throw errors;
  2293. }
  2294. this.type = this.type.toUpperCase();
  2295. // set request, response content type headers
  2296. var headers = this.setHeaders(params, opts, this.operation);
  2297. var body = params.body;
  2298. // encode the body for form submits
  2299. if (headers['Content-Type']) {
  2300. var key, value, values = {}, i;
  2301. var operationParams = this.operation.parameters;
  2302. for (i = 0; i < operationParams.length; i++) {
  2303. var param = operationParams[i];
  2304. if (param.paramType === 'form')
  2305. values[param.name] = param;
  2306. }
  2307. if (headers['Content-Type'].indexOf('application/x-www-form-urlencoded') === 0) {
  2308. var encoded = '';
  2309. for (key in values) {
  2310. value = this.params[key];
  2311. if (typeof value !== 'undefined') {
  2312. if (encoded !== '')
  2313. encoded += '&';
  2314. encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
  2315. }
  2316. }
  2317. body = encoded;
  2318. }
  2319. else if (headers['Content-Type'].indexOf('multipart/form-data') === 0) {
  2320. // encode the body for form submits
  2321. var data = '';
  2322. var boundary = '----SwaggerFormBoundary' + Date.now();
  2323. for (key in values) {
  2324. value = this.params[key];
  2325. if (typeof value !== 'undefined') {
  2326. data += '--' + boundary + '\n';
  2327. data += 'Content-Disposition: form-data; name="' + key + '"';
  2328. data += '\n\n';
  2329. data += value + '\n';
  2330. }
  2331. }
  2332. data += '--' + boundary + '--\n';
  2333. headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
  2334. body = data;
  2335. }
  2336. }
  2337. var obj;
  2338. if (!((this.headers != null) && (this.headers.mock != null))) {
  2339. obj = {
  2340. url: this.url,
  2341. method: this.type,
  2342. headers: headers,
  2343. body: body,
  2344. useJQuery: this.useJQuery,
  2345. on: {
  2346. error: function (response) {
  2347. return _this.errorCallback(response, _this.opts.parent);
  2348. },
  2349. redirect: function (response) {
  2350. return _this.successCallback(response, _this.opts.parent);
  2351. },
  2352. 307: function (response) {
  2353. return _this.successCallback(response, _this.opts.parent);
  2354. },
  2355. response: function (response) {
  2356. return _this.successCallback(response, _this.opts.parent);
  2357. }
  2358. }
  2359. };
  2360. var status = false;
  2361. if (this.operation.resource && this.operation.resource.api && this.operation.resource.api.clientAuthorizations) {
  2362. // Get the client authorizations from the resource declaration
  2363. status = this.operation.resource.api.clientAuthorizations.apply(obj, this.operation.authorizations);
  2364. } else {
  2365. // Get the client authorization from the default authorization declaration
  2366. var e;
  2367. if (typeof window !== 'undefined') {
  2368. e = window;
  2369. } else {
  2370. e = exports;
  2371. }
  2372. status = e.authorizations.apply(obj, this.operation.authorizations);
  2373. }
  2374. if (!opts.mock) {
  2375. if (status !== false) {
  2376. new SwaggerHttp().execute(obj);
  2377. } else {
  2378. obj.canceled = true;
  2379. }
  2380. } else {
  2381. return obj;
  2382. }
  2383. }
  2384. return obj;
  2385. };
  2386. SwaggerRequest.prototype.setHeaders = function (params, opts, operation) {
  2387. // default type
  2388. var accepts = opts.responseContentType || 'application/json';
  2389. var consumes = opts.requestContentType || 'application/json';
  2390. var allDefinedParams = operation.parameters;
  2391. var definedFormParams = [];
  2392. var definedFileParams = [];
  2393. var body = params.body;
  2394. var headers = {};
  2395. // get params from the operation and set them in definedFileParams, definedFormParams, headers
  2396. var i;
  2397. for (i = 0; i < allDefinedParams.length; i++) {
  2398. var param = allDefinedParams[i];
  2399. if (param.paramType === 'form')
  2400. definedFormParams.push(param);
  2401. else if (param.paramType === 'file')
  2402. definedFileParams.push(param);
  2403. else if (param.paramType === 'header' && this.params.headers) {
  2404. var key = param.name;
  2405. var headerValue = this.params.headers[param.name];
  2406. if (typeof this.params.headers[param.name] !== 'undefined')
  2407. headers[key] = headerValue;
  2408. }
  2409. }
  2410. // if there's a body, need to set the accepts header via requestContentType
  2411. if (body && (this.type === 'POST' || this.type === 'PUT' || this.type === 'PATCH' || this.type === 'DELETE')) {
  2412. if (this.opts.requestContentType)
  2413. consumes = this.opts.requestContentType;
  2414. } else {
  2415. // if any form params, content type must be set
  2416. if (definedFormParams.length > 0) {
  2417. if (definedFileParams.length > 0)
  2418. consumes = 'multipart/form-data';
  2419. else
  2420. consumes = 'application/x-www-form-urlencoded';
  2421. }
  2422. else if (this.type === 'DELETE')
  2423. body = '{}';
  2424. else if (this.type != 'DELETE')
  2425. consumes = null;
  2426. }
  2427. if (consumes && this.operation.consumes) {
  2428. if (this.operation.consumes.indexOf(consumes) === -1) {
  2429. log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.operation.consumes));
  2430. }
  2431. }
  2432. if (this.opts && this.opts.responseContentType) {
  2433. accepts = this.opts.responseContentType;
  2434. } else {
  2435. accepts = 'application/json';
  2436. }
  2437. if (accepts && operation.produces) {
  2438. if (operation.produces.indexOf(accepts) === -1) {
  2439. log('server can\'t produce ' + accepts);
  2440. }
  2441. }
  2442. if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded'))
  2443. headers['Content-Type'] = consumes;
  2444. if (accepts)
  2445. headers.Accept = accepts;
  2446. return headers;
  2447. };
  2448. /**
  2449. * SwaggerHttp is a wrapper for executing requests
  2450. */
  2451. var SwaggerHttp = function() {};
  2452. SwaggerHttp.prototype.execute = function(obj) {
  2453. if(obj && (typeof obj.useJQuery === 'boolean'))
  2454. this.useJQuery = obj.useJQuery;
  2455. else
  2456. this.useJQuery = this.isIE8();
  2457. if(obj && typeof obj.body === 'object') {
  2458. obj.body = JSON.stringify(obj.body);
  2459. }
  2460. if(this.useJQuery)
  2461. return new JQueryHttpClient().execute(obj);
  2462. else
  2463. return new ShredHttpClient().execute(obj);
  2464. };
  2465. SwaggerHttp.prototype.isIE8 = function() {
  2466. var detectedIE = false;
  2467. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  2468. nav = navigator.userAgent.toLowerCase();
  2469. if (nav.indexOf('msie') !== -1) {
  2470. var version = parseInt(nav.split('msie')[1]);
  2471. if (version <= 8) {
  2472. detectedIE = true;
  2473. }
  2474. }
  2475. }
  2476. return detectedIE;
  2477. };
  2478. /*
  2479. * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic.
  2480. * NOTE: when jQuery is available it will export both '$' and 'jQuery' to the global space.
  2481. * Since we are using closures here we need to alias it for internal use.
  2482. */
  2483. var JQueryHttpClient = function(options) {
  2484. "use strict";
  2485. if(!jQuery){
  2486. var jQuery = window.jQuery;
  2487. }
  2488. };
  2489. JQueryHttpClient.prototype.execute = function(obj) {
  2490. var cb = obj.on;
  2491. var request = obj;
  2492. obj.type = obj.method;
  2493. obj.cache = false;
  2494. obj.beforeSend = function(xhr) {
  2495. var key, results;
  2496. if (obj.headers) {
  2497. results = [];
  2498. for (key in obj.headers) {
  2499. if (key.toLowerCase() === "content-type") {
  2500. results.push(obj.contentType = obj.headers[key]);
  2501. } else if (key.toLowerCase() === "accept") {
  2502. results.push(obj.accepts = obj.headers[key]);
  2503. } else {
  2504. results.push(xhr.setRequestHeader(key, obj.headers[key]));
  2505. }
  2506. }
  2507. return results;
  2508. }
  2509. };
  2510. obj.data = obj.body;
  2511. obj.complete = function(response, textStatus, opts) {
  2512. var headers = {},
  2513. headerArray = response.getAllResponseHeaders().split("\n");
  2514. for(var i = 0; i < headerArray.length; i++) {
  2515. var toSplit = headerArray[i].trim();
  2516. if(toSplit.length === 0)
  2517. continue;
  2518. var separator = toSplit.indexOf(":");
  2519. if(separator === -1) {
  2520. // Name but no value in the header
  2521. headers[toSplit] = null;
  2522. continue;
  2523. }
  2524. var name = toSplit.substring(0, separator).trim(),
  2525. value = toSplit.substring(separator + 1).trim();
  2526. headers[name] = value;
  2527. }
  2528. var out = {
  2529. url: request.url,
  2530. method: request.method,
  2531. status: response.status,
  2532. data: response.responseText,
  2533. headers: headers
  2534. };
  2535. var contentType = (headers["content-type"]||headers["Content-Type"]||null);
  2536. if(contentType) {
  2537. if(contentType.indexOf("application/json") === 0 || contentType.indexOf("+json") > 0) {
  2538. try {
  2539. out.obj = response.responseJSON || {};
  2540. } catch (ex) {
  2541. // do not set out.obj
  2542. log("unable to parse JSON content");
  2543. }
  2544. }
  2545. }
  2546. if(response.status >= 200 && response.status < 300)
  2547. cb.response(out);
  2548. else if(response.status === 0 || (response.status >= 400 && response.status < 599))
  2549. cb.error(out);
  2550. else
  2551. return cb.response(out);
  2552. };
  2553. jQuery.support.cors = true;
  2554. return jQuery.ajax(obj);
  2555. };
  2556. /*
  2557. * ShredHttpClient is a light-weight, node or browser HTTP client
  2558. */
  2559. var ShredHttpClient = function(options) {
  2560. this.options = (options||{});
  2561. this.isInitialized = false;
  2562. var identity, toString;
  2563. if (typeof window !== 'undefined') {
  2564. this.Shred = require("./shred");
  2565. this.content = require("./shred/content");
  2566. }
  2567. else
  2568. this.Shred = require("shred");
  2569. this.shred = new this.Shred(options);
  2570. };
  2571. ShredHttpClient.prototype.initShred = function () {
  2572. this.isInitialized = true;
  2573. this.registerProcessors(this.shred);
  2574. };
  2575. ShredHttpClient.prototype.registerProcessors = function(shred) {
  2576. var identity = function(x) {
  2577. return x;
  2578. };
  2579. var toString = function(x) {
  2580. return x.toString();
  2581. };
  2582. if (typeof window !== 'undefined') {
  2583. this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
  2584. parser: identity,
  2585. stringify: toString
  2586. });
  2587. } else {
  2588. this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
  2589. parser: identity,
  2590. stringify: toString
  2591. });
  2592. }
  2593. };
  2594. ShredHttpClient.prototype.execute = function(obj) {
  2595. if(!this.isInitialized)
  2596. this.initShred();
  2597. var cb = obj.on, res;
  2598. var transform = function(response) {
  2599. var out = {
  2600. headers: response._headers,
  2601. url: response.request.url,
  2602. method: response.request.method,
  2603. status: response.status,
  2604. data: response.content.data
  2605. };
  2606. var headers = response._headers.normalized || response._headers;
  2607. var contentType = (headers["content-type"]||headers["Content-Type"]||null);
  2608. if(contentType) {
  2609. if(contentType.indexOf("application/json") === 0 || contentType.indexOf("+json") > 0) {
  2610. if(response.content.data && response.content.data !== "")
  2611. try{
  2612. out.obj = JSON.parse(response.content.data);
  2613. }
  2614. catch (e) {
  2615. // unable to parse
  2616. }
  2617. else
  2618. out.obj = {};
  2619. }
  2620. }
  2621. return out;
  2622. };
  2623. // Transform an error into a usable response-like object
  2624. var transformError = function (error) {
  2625. var out = {
  2626. // Default to a status of 0 - The client will treat this as a generic permissions sort of error
  2627. status: 0,
  2628. data: error.message || error
  2629. };
  2630. if (error.code) {
  2631. out.obj = error;
  2632. if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
  2633. // We can tell the client that this should be treated as a missing resource and not as a permissions thing
  2634. out.status = 404;
  2635. }
  2636. }
  2637. return out;
  2638. };
  2639. res = {
  2640. error: function (response) {
  2641. if (obj)
  2642. return cb.error(transform(response));
  2643. },
  2644. // Catch the Shred error raised when the request errors as it is made (i.e. No Response is coming)
  2645. request_error: function (err) {
  2646. if (obj)
  2647. return cb.error(transformError(err));
  2648. },
  2649. response: function (response) {
  2650. if (obj) {
  2651. return cb.response(transform(response));
  2652. }
  2653. }
  2654. };
  2655. if (obj) {
  2656. obj.on = res;
  2657. }
  2658. return this.shred.request(obj);
  2659. };
  2660. var e = (typeof window !== 'undefined' ? window : exports);
  2661. e.authorizations = new SwaggerAuthorizations();
  2662. e.ApiKeyAuthorization = ApiKeyAuthorization;
  2663. e.PasswordAuthorization = PasswordAuthorization;
  2664. e.CookieAuthorization = CookieAuthorization;
  2665. e.SwaggerClient = SwaggerClient;
  2666. e.Operation = Operation;
  2667. e.Model = Model;
  2668. e.models = models;
  2669. })();