25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

swagger-client.js 36 KiB

10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
10 yıl önce
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  1. // swagger-client.js
  2. // version 2.1.0
  3. /**
  4. * SwaggerAuthorizations applys the correct authorization to an operation being executed
  5. */
  6. var SwaggerAuthorizations = function() {
  7. this.authz = {};
  8. };
  9. SwaggerAuthorizations.prototype.add = function(name, auth) {
  10. this.authz[name] = auth;
  11. return auth;
  12. };
  13. SwaggerAuthorizations.prototype.remove = function(name) {
  14. return delete this.authz[name];
  15. };
  16. SwaggerAuthorizations.prototype.apply = function(obj, authorizations) {
  17. var status = null;
  18. var key;
  19. // if the "authorizations" key is undefined, or has an empty array, add all keys
  20. if(typeof authorizations === 'undefined' || Object.keys(authorizations).length == 0) {
  21. for (key in this.authz) {
  22. value = this.authz[key];
  23. result = value.apply(obj, authorizations);
  24. if (result === true)
  25. status = true;
  26. }
  27. }
  28. else {
  29. for(name in authorizations) {
  30. for (key in this.authz) {
  31. if(key == name) {
  32. value = this.authz[key];
  33. result = value.apply(obj, authorizations);
  34. if (result === true)
  35. status = true;
  36. }
  37. }
  38. }
  39. }
  40. return status;
  41. };
  42. /**
  43. * ApiKeyAuthorization allows a query param or header to be injected
  44. */
  45. var ApiKeyAuthorization = function(name, value, type) {
  46. this.name = name;
  47. this.value = value;
  48. this.type = type;
  49. };
  50. ApiKeyAuthorization.prototype.apply = function(obj, authorizations) {
  51. if (this.type === "query") {
  52. if (obj.url.indexOf('?') > 0)
  53. obj.url = obj.url + "&" + this.name + "=" + this.value;
  54. else
  55. obj.url = obj.url + "?" + this.name + "=" + this.value;
  56. return true;
  57. } else if (this.type === "header") {
  58. obj.headers[this.name] = this.value;
  59. return true;
  60. }
  61. };
  62. var CookieAuthorization = function(cookie) {
  63. this.cookie = cookie;
  64. }
  65. CookieAuthorization.prototype.apply = function(obj, authorizations) {
  66. obj.cookieJar = obj.cookieJar || CookieJar();
  67. obj.cookieJar.setCookie(this.cookie);
  68. return true;
  69. }
  70. /**
  71. * Password Authorization is a basic auth implementation
  72. */
  73. var PasswordAuthorization = function(name, username, password) {
  74. this.name = name;
  75. this.username = username;
  76. this.password = password;
  77. this._btoa = null;
  78. if (typeof window !== 'undefined')
  79. this._btoa = btoa;
  80. else
  81. this._btoa = require("btoa");
  82. };
  83. PasswordAuthorization.prototype.apply = function(obj, authorizations) {
  84. var base64encoder = this._btoa;
  85. obj.headers["Authorization"] = "Basic " + base64encoder(this.username + ":" + this.password);
  86. return true;
  87. };var __bind = function(fn, me){
  88. return function(){
  89. return fn.apply(me, arguments);
  90. };
  91. };
  92. fail = function(message) {
  93. log(message);
  94. }
  95. log = function(){
  96. log.history = log.history || [];
  97. log.history.push(arguments);
  98. if(this.console){
  99. console.log( Array.prototype.slice.call(arguments)[0] );
  100. }
  101. };
  102. if (!Array.prototype.indexOf) {
  103. Array.prototype.indexOf = function(obj, start) {
  104. for (var i = (start || 0), j = this.length; i < j; i++) {
  105. if (this[i] === obj) { return i; }
  106. }
  107. return -1;
  108. }
  109. }
  110. if (!('filter' in Array.prototype)) {
  111. Array.prototype.filter= function(filter, that /*opt*/) {
  112. var other= [], v;
  113. for (var i=0, n= this.length; i<n; i++)
  114. if (i in this && filter.call(that, v= this[i], i, this))
  115. other.push(v);
  116. return other;
  117. };
  118. }
  119. if (!('map' in Array.prototype)) {
  120. Array.prototype.map= function(mapper, that /*opt*/) {
  121. var other= new Array(this.length);
  122. for (var i= 0, n= this.length; i<n; i++)
  123. if (i in this)
  124. other[i]= mapper.call(that, this[i], i, this);
  125. return other;
  126. };
  127. }
  128. Object.keys = Object.keys || (function () {
  129. var hasOwnProperty = Object.prototype.hasOwnProperty,
  130. hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
  131. DontEnums = [
  132. 'toString',
  133. 'toLocaleString',
  134. 'valueOf',
  135. 'hasOwnProperty',
  136. 'isPrototypeOf',
  137. 'propertyIsEnumerable',
  138. 'constructor'
  139. ],
  140. DontEnumsLength = DontEnums.length;
  141. return function (o) {
  142. if (typeof o != "object" && typeof o != "function" || o === null)
  143. throw new TypeError("Object.keys called on a non-object");
  144. var result = [];
  145. for (var name in o) {
  146. if (hasOwnProperty.call(o, name))
  147. result.push(name);
  148. }
  149. if (hasDontEnumBug) {
  150. for (var i = 0; i < DontEnumsLength; i++) {
  151. if (hasOwnProperty.call(o, DontEnums[i]))
  152. result.push(DontEnums[i]);
  153. }
  154. }
  155. return result;
  156. };
  157. })();
  158. var SwaggerClient = function(url, options) {
  159. this.isBuilt = false;
  160. this.url = null;
  161. this.debug = false;
  162. this.basePath = null;
  163. this.authorizations = null;
  164. this.authorizationScheme = null;
  165. this.isValid = false;
  166. this.info = null;
  167. this.useJQuery = false;
  168. this.models = models;
  169. options = (options||{});
  170. if (url)
  171. if (url.url) options = url;
  172. else this.url = url;
  173. else options = url;
  174. if (options.url != null)
  175. this.url = options.url;
  176. if (options.success != null)
  177. this.success = options.success;
  178. if (typeof options.useJQuery === 'boolean')
  179. this.useJQuery = options.useJQuery;
  180. this.failure = options.failure != null ? options.failure : function() {};
  181. this.progress = options.progress != null ? options.progress : function() {};
  182. this.spec = options.spec;
  183. if (options.success != null)
  184. this.build();
  185. }
  186. SwaggerClient.prototype.build = function() {
  187. var self = this;
  188. this.progress('fetching resource list: ' + this.url);
  189. var obj = {
  190. useJQuery: this.useJQuery,
  191. url: this.url,
  192. method: "get",
  193. headers: {
  194. accept: "application/json, */*"
  195. },
  196. on: {
  197. error: function(response) {
  198. if (self.url.substring(0, 4) !== 'http')
  199. return self.fail('Please specify the protocol for ' + self.url);
  200. else if (response.status === 0)
  201. return self.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.');
  202. else if (response.status === 404)
  203. return self.fail('Can\'t read swagger JSON from ' + self.url);
  204. else
  205. return self.fail(response.status + ' : ' + response.statusText + ' ' + self.url);
  206. },
  207. response: function(resp) {
  208. var responseObj = resp.obj || JSON.parse(resp.data);
  209. self.swaggerVersion = responseObj.swaggerVersion;
  210. if(responseObj.swagger && responseObj.swagger === 2.0) {
  211. self.swaggerVersion = responseObj.swagger;
  212. self.buildFromSpec(responseObj);
  213. self.isValid = true;
  214. }
  215. else {
  216. self.isValid = false;
  217. self.failure();
  218. }
  219. }
  220. }
  221. };
  222. if(this.spec) {
  223. var self = this;
  224. setTimeout(function() {
  225. self.buildFromSpec(self.spec);
  226. }, 10);
  227. }
  228. else {
  229. var e = (typeof window !== 'undefined' ? window : exports);
  230. var status = e.authorizations.apply(obj);
  231. new SwaggerHttp().execute(obj);
  232. }
  233. return this;
  234. };
  235. SwaggerClient.prototype.buildFromSpec = function(response) {
  236. if(this.isBuilt)
  237. return this;
  238. this.info = response.info || {};
  239. this.title = response.title || '';
  240. this.host = response.host || '';
  241. this.schemes = response.schemes || [ 'http' ];
  242. this.basePath = response.basePath || '';
  243. this.apis = {};
  244. this.apisArray = [];
  245. this.consumes = response.consumes;
  246. this.produces = response.produces;
  247. this.authSchemes = response.authorizations;
  248. if(typeof this.host === 'undefined' || this.host === '') {
  249. var location = this.parseUri(this.url);
  250. this.host = location.host;
  251. }
  252. this.definitions = response.definitions;
  253. var key;
  254. for(key in this.definitions) {
  255. var model = new Model(key, this.definitions[key]);
  256. if(model) {
  257. models[key] = model;
  258. }
  259. }
  260. // get paths, create functions for each operationId
  261. var path;
  262. var operations = [];
  263. for(path in response.paths) {
  264. var httpMethod;
  265. for(httpMethod in response.paths[path]) {
  266. var operation = response.paths[path][httpMethod];
  267. var tags = operation.tags;
  268. if(typeof tags === 'undefined') {
  269. operation.tags = [ 'default' ];
  270. tags = operation.tags;
  271. }
  272. var operationId = this.idFromOp(path, httpMethod, operation);
  273. var operation = new Operation (
  274. this,
  275. operationId,
  276. httpMethod,
  277. path,
  278. operation,
  279. this.definitions
  280. );
  281. // bind this operation's execute command to the api
  282. if(tags.length > 0) {
  283. var i;
  284. for(i = 0; i < tags.length; i++) {
  285. var tag = this.tagFromLabel(tags[i]);
  286. var operationGroup = this[tag];
  287. if(typeof operationGroup === 'undefined') {
  288. this[tag] = [];
  289. operationGroup = this[tag];
  290. operationGroup.label = tag;
  291. operationGroup.apis = [];
  292. this[tag].help = this.help.bind(operationGroup);
  293. this.apisArray.push(new OperationGroup(tag, operation));
  294. }
  295. operationGroup[operationId] = operation.execute.bind(operation);
  296. operationGroup[operationId].help = operation.help.bind(operation);
  297. operationGroup.apis.push(operation);
  298. // legacy UI feature
  299. var j;
  300. var api = null;
  301. for(j = 0; j < this.apisArray.length; j++) {
  302. if(this.apisArray[j].tag === tag) {
  303. api = this.apisArray[j];
  304. }
  305. }
  306. if(api) {
  307. api.operationsArray.push(operation);
  308. }
  309. }
  310. }
  311. else {
  312. log('no group to bind to');
  313. }
  314. }
  315. }
  316. this.isBuilt = true;
  317. if (this.success)
  318. this.success();
  319. return this;
  320. }
  321. SwaggerClient.prototype.parseUri = function(uri) {
  322. var urlParseRE = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/;
  323. var parts = urlParseRE.exec(uri);
  324. return {
  325. scheme: parts[4].replace(':',''),
  326. host: parts[11],
  327. path: parts[15]
  328. };
  329. }
  330. SwaggerClient.prototype.help = function() {
  331. var i;
  332. log('operations for the "' + this.label + '" tag');
  333. for(i = 0; i < this.apis.length; i++) {
  334. var api = this.apis[i];
  335. log(' * ' + api.nickname + ': ' + api.operation.summary);
  336. }
  337. }
  338. SwaggerClient.prototype.tagFromLabel = function(label) {
  339. return label;
  340. }
  341. SwaggerClient.prototype.idFromOp = function(path, httpMethod, op) {
  342. if(typeof op.operationId !== 'undefined') {
  343. return (op.operationId);
  344. }
  345. else {
  346. return path.substring(1).replace(/\//g, "_").replace(/\{/g, "").replace(/\}/g, "") + "_" + httpMethod;
  347. }
  348. }
  349. SwaggerClient.prototype.fail = function(message) {
  350. this.failure(message);
  351. throw message;
  352. };
  353. var OperationGroup = function(tag, operation) {
  354. this.tag = tag;
  355. this.path = tag;
  356. this.name = tag;
  357. this.operation = operation;
  358. this.operationsArray = [];
  359. this.description = operation.description || "";
  360. }
  361. var Operation = function(parent, operationId, httpMethod, path, args, definitions) {
  362. var errors = [];
  363. this.operation = args;
  364. this.consumes = args.consumes;
  365. this.produces = args.produces;
  366. this.parent = parent;
  367. this.host = parent.host;
  368. this.schemes = parent.schemes;
  369. this.basePath = parent.basePath;
  370. this.nickname = (operationId||errors.push('Operations must have a nickname.'));
  371. this.method = (httpMethod||errors.push('Operation ' + operationId + ' is missing method.'));
  372. this.path = (path||errors.push('Operation ' + nickname + ' is missing path.'));
  373. this.parameters = args != null ? (args.parameters||[]) : {};
  374. this.summary = args.summary || '';
  375. this.responses = (args.responses||{});
  376. this.type = null;
  377. this.security = args.security;
  378. this.description = args.description;
  379. var i;
  380. for(i = 0; i < this.parameters.length; i++) {
  381. var param = this.parameters[i];
  382. type = this.getType(param);
  383. param.signature = this.getSignature(type, models);
  384. param.sampleJSON = this.getSampleJSON(type, models);
  385. param.responseClassSignature = param.signature;
  386. }
  387. var response;
  388. var model;
  389. var responses = this.responses;
  390. if(responses['200']) {
  391. response = responses['200'];
  392. defaultResponseCode = '200';
  393. }
  394. else if(responses['default']) {
  395. response = responses['default'];
  396. defaultResponseCode = 'default';
  397. }
  398. if(response && response.schema) {
  399. var resolvedModel = this.resolveModel(response.schema, definitions);
  400. if(resolvedModel) {
  401. this.type = resolvedModel.name;
  402. this.responseSampleJSON = JSON.stringify(resolvedModel.getSampleValue(), null, 2);
  403. this.responseClassSignature = resolvedModel.getMockSignature();
  404. delete responses[defaultResponseCode];
  405. }
  406. else {
  407. this.type = response.schema.type;
  408. }
  409. }
  410. if (errors.length > 0)
  411. this.resource.api.fail(errors);
  412. return this;
  413. }
  414. OperationGroup.prototype.sort = function(sorter) {
  415. }
  416. Operation.prototype.getType = function (param) {
  417. var type = param.type;
  418. var format = param.format;
  419. var isArray = false;
  420. var str;
  421. if(type === 'integer' && format === 'int32')
  422. str = 'integer';
  423. else if(type === 'integer' && format === 'int64')
  424. str = 'long';
  425. else if(type === 'string' && format === 'date-time')
  426. str = 'date-time';
  427. else if(type === 'string' && format === 'date')
  428. str = 'date';
  429. else if(type === 'number' && format === 'float')
  430. str = 'float';
  431. else if(type === 'number' && format === 'double')
  432. str = 'double';
  433. else if(type === 'boolean')
  434. str = 'boolean';
  435. else if(type === 'string')
  436. str = 'string';
  437. else if(type === 'array') {
  438. isArray = true;
  439. if(param.items)
  440. str = this.getType(param.items);
  441. }
  442. if(param['$ref'])
  443. str = param['$ref'];
  444. var schema = param.schema;
  445. if(schema) {
  446. var ref = schema['$ref'];
  447. if(ref) {
  448. ref = simpleRef(ref);
  449. if(isArray)
  450. return [ ref ];
  451. else
  452. return ref;
  453. }
  454. else
  455. return this.getType(schema);
  456. }
  457. if(isArray)
  458. return [ str ];
  459. else
  460. return str;
  461. }
  462. Operation.prototype.resolveModel = function (schema, definitions) {
  463. if(typeof schema['$ref'] !== 'undefined') {
  464. var ref = schema['$ref'];
  465. if(ref.indexOf('#/definitions/') == 0)
  466. ref = ref.substring('#/definitions/'.length);
  467. if(definitions[ref])
  468. return new Model(ref, definitions[ref]);
  469. }
  470. if(schema.type === 'array')
  471. return new ArrayModel(schema);
  472. else
  473. return null;
  474. }
  475. Operation.prototype.help = function() {
  476. log(this.nickname + ': ' + this.operation.summary);
  477. for(var i = 0; i < this.parameters.length; i++) {
  478. var param = this.parameters[i];
  479. log(' * ' + param.name + ': ' + param.description);
  480. }
  481. }
  482. Operation.prototype.getSignature = function(type, models) {
  483. var isPrimitive, listType;
  484. if(type instanceof Array) {
  485. listType = true;
  486. type = type[0];
  487. }
  488. if(type === 'string')
  489. isPrimitive = true
  490. else
  491. isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
  492. if (isPrimitive) {
  493. return type;
  494. } else {
  495. if (listType != null) {
  496. return models[type].getMockSignature();
  497. } else {
  498. return models[type].getMockSignature();
  499. }
  500. }
  501. };
  502. Operation.prototype.getSampleJSON = function(type, models) {
  503. var isPrimitive, listType, sampleJson;
  504. listType = (type instanceof Array);
  505. isPrimitive = (models[type] != null) ? false : true;
  506. sampleJson = isPrimitive ? void 0 : models[type].createJSONSample();
  507. if (sampleJson) {
  508. sampleJson = listType ? [sampleJson] : sampleJson;
  509. if(typeof sampleJson == 'string')
  510. return sampleJson;
  511. else if(typeof sampleJson === 'object') {
  512. var t = sampleJson;
  513. if(sampleJson instanceof Array && sampleJson.length > 0) {
  514. t = sampleJson[0];
  515. }
  516. if(t.nodeName) {
  517. var xmlString = new XMLSerializer().serializeToString(t);
  518. return this.formatXml(xmlString);
  519. }
  520. else
  521. return JSON.stringify(sampleJson, null, 2);
  522. }
  523. else
  524. return sampleJson;
  525. }
  526. };
  527. // legacy support
  528. Operation.prototype["do"] = function(args, opts, callback, error, parent) {
  529. return this.execute(args, opts, callback, error, parent);
  530. }
  531. Operation.prototype.execute = function(arg1, arg2, arg3, arg4, parent) {
  532. var args = (arg1||{});
  533. var opts = {}, success, error;
  534. if(typeof arg2 === 'object') {
  535. opts = arg2;
  536. success = arg3;
  537. error = arg4;
  538. }
  539. if(typeof arg2 === 'function') {
  540. success = arg2;
  541. error = arg3;
  542. }
  543. var formParams = {};
  544. var headers = {};
  545. var requestUrl = this.path;
  546. success = (success||log)
  547. error = (error||log)
  548. var requiredParams = [];
  549. var missingParams = [];
  550. // check required params
  551. for(var i = 0; i < this.parameters.length; i++) {
  552. var param = this.parameters[i];
  553. if(param.required === true) {
  554. requiredParams.push(param.name);
  555. if(typeof args[param.name] === 'undefined')
  556. missingParams = param.name;
  557. }
  558. }
  559. if(missingParams.length > 0) {
  560. var message = 'missing required params: ' + missingParams;
  561. fail(message);
  562. return;
  563. }
  564. // set content type negotiation
  565. var consumes = this.consumes || this.parent.consumes || [ 'application/json' ];
  566. var produces = this.produces || this.parent.produces || [ 'application/json' ];
  567. headers = this.setContentTypes(args, opts);
  568. // grab params from the args, build the querystring along the way
  569. var querystring = "";
  570. for(var i = 0; i < this.parameters.length; i++) {
  571. var param = this.parameters[i];
  572. if(typeof args[param.name] !== 'undefined') {
  573. if(param.in === 'path') {
  574. var reg = new RegExp('\{' + param.name + '[^\}]*\}', 'gi');
  575. requestUrl = requestUrl.replace(reg, this.encodePathParam(args[param.name]));
  576. }
  577. else if (param.in === 'query') {
  578. if(querystring === '')
  579. querystring += '?';
  580. else
  581. querystring += '&';
  582. if(typeof param.collectionFormat !== 'undefined') {
  583. var qp = args[param.name];
  584. if(Array.isArray(qp))
  585. querystring += this.encodeCollection(param.collectionFormat, param.name, qp);
  586. else
  587. querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
  588. }
  589. else
  590. querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
  591. }
  592. else if (param.in === 'header')
  593. headers[param.name] = args[param.name];
  594. else if (param.in === 'form')
  595. formParams[param.name] = args[param.name];
  596. }
  597. }
  598. var scheme = this.schemes[0];
  599. var url = scheme + '://' + this.host + this.basePath + requestUrl + querystring;
  600. var obj = {
  601. url: url,
  602. method: this.method,
  603. useJQuery: this.useJQuery,
  604. headers: headers,
  605. on: {
  606. response: function(response) {
  607. return success(response, parent);
  608. },
  609. error: function(response) {
  610. return error(response, parent);
  611. }
  612. }
  613. };
  614. var status = e.authorizations.apply(obj, this.operation.security);
  615. new SwaggerHttp().execute(obj);
  616. }
  617. Operation.prototype.setContentTypes = function(args, opts) {
  618. // default type
  619. var accepts = 'application/json';
  620. var consumes = 'application/json';
  621. var allDefinedParams = this.parameters;
  622. var definedFormParams = [];
  623. var definedFileParams = [];
  624. var body = args.body;
  625. var headers = {};
  626. // get params from the operation and set them in definedFileParams, definedFormParams, headers
  627. var i;
  628. for(i = 0; i < allDefinedParams.length; i++) {
  629. var param = allDefinedParams[i];
  630. if(param.in === 'form')
  631. definedFormParams.push(param);
  632. else if(param.in === 'file')
  633. definedFileParams.push(param);
  634. else if(param.in === 'header' && this.params.headers) {
  635. var key = param.name;
  636. var headerValue = this.params.headers[param.name];
  637. if(typeof this.params.headers[param.name] !== 'undefined')
  638. headers[key] = headerValue;
  639. }
  640. }
  641. // if there's a body, need to set the accepts header via requestContentType
  642. if (body && (this.type === 'post' || this.type === 'put' || this.type === 'patch' || this.type === 'delete')) {
  643. if (opts.requestContentType)
  644. consumes = opts.requestContentType;
  645. } else {
  646. // if any form params, content type must be set
  647. if(definedFormParams.length > 0) {
  648. if(definedFileParams.length > 0)
  649. consumes = 'multipart/form-data';
  650. else
  651. consumes = 'application/x-www-form-urlencoded';
  652. }
  653. else if (this.type == 'DELETE')
  654. body = '{}';
  655. else if (this.type != 'DELETE')
  656. accepts = null;
  657. }
  658. if (consumes && this.consumes) {
  659. if (this.consumes.indexOf(consumes) === -1) {
  660. log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.consumes));
  661. consumes = this.operation.consumes[0];
  662. }
  663. }
  664. if (opts.responseContentType) {
  665. accepts = opts.responseContentType;
  666. } else {
  667. accepts = 'application/json';
  668. }
  669. if (accepts && this.produces) {
  670. if (this.produces.indexOf(accepts) === -1) {
  671. log('server can\'t produce ' + accepts);
  672. accepts = this.produces[0];
  673. }
  674. }
  675. if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded'))
  676. headers['Content-Type'] = consumes;
  677. if (accepts)
  678. headers['Accept'] = accepts;
  679. return headers;
  680. }
  681. Operation.prototype.encodeCollection = function(type, name, value) {
  682. var encoded = '';
  683. var i;
  684. if(type === 'jaxrs') {
  685. for(i = 0; i < value.length; i++) {
  686. if(i > 0) encoded += '&'
  687. encoded += this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
  688. }
  689. }
  690. return encoded;
  691. }
  692. Operation.prototype.encodeQueryParam = function(arg) {
  693. return escape(arg);
  694. }
  695. Operation.prototype.encodePathParam = function(pathParam) {
  696. var encParts, part, parts, _i, _len;
  697. pathParam = pathParam.toString();
  698. if (pathParam.indexOf('/') === -1) {
  699. return encodeURIComponent(pathParam);
  700. } else {
  701. parts = pathParam.split('/');
  702. encParts = [];
  703. for (_i = 0, _len = parts.length; _i < _len; _i++) {
  704. part = parts[_i];
  705. encParts.push(encodeURIComponent(part));
  706. }
  707. return encParts.join('/');
  708. }
  709. };
  710. Operation.prototype.encodePathParam = function(pathParam) {
  711. var encParts, part, parts, _i, _len;
  712. pathParam = pathParam.toString();
  713. if (pathParam.indexOf('/') === -1) {
  714. return encodeURIComponent(pathParam);
  715. } else {
  716. parts = pathParam.split('/');
  717. encParts = [];
  718. for (_i = 0, _len = parts.length; _i < _len; _i++) {
  719. part = parts[_i];
  720. encParts.push(encodeURIComponent(part));
  721. }
  722. return encParts.join('/');
  723. }
  724. };
  725. var ArrayModel = function(definition) {
  726. this.name = "name";
  727. this.definition = definition || {};
  728. this.properties = [];
  729. this.type;
  730. this.ref;
  731. var requiredFields = definition.enum || [];
  732. var items = definition.items;
  733. if(items) {
  734. var type = items.type;
  735. if(items.type) {
  736. this.type = typeFromJsonSchema(type.type, type.format);
  737. }
  738. else {
  739. this.ref = items['$ref'];
  740. }
  741. }
  742. }
  743. ArrayModel.prototype.createJSONSample = function(modelsToIgnore) {
  744. var result;
  745. var modelsToIgnore = (modelsToIgnore||[])
  746. if(this.type) {
  747. result = type;
  748. }
  749. else if (this.ref) {
  750. var name = simpleRef(this.ref);
  751. result = models[name].createJSONSample();
  752. }
  753. return [ result ];
  754. };
  755. ArrayModel.prototype.getSampleValue = function() {
  756. var result;
  757. var modelsToIgnore = (modelsToIgnore||[])
  758. if(this.type) {
  759. result = type;
  760. }
  761. else if (this.ref) {
  762. var name = simpleRef(this.ref);
  763. result = models[name].getSampleValue();
  764. }
  765. return [ result ];
  766. }
  767. ArrayModel.prototype.getMockSignature = function(modelsToIgnore) {
  768. var propertiesStr = [];
  769. if(this.ref) {
  770. return models[simpleRef(this.ref)].getMockSignature();
  771. }
  772. };
  773. var PrimitiveModel = function(definition) {
  774. this.name = "name";
  775. this.definition = definition || {};
  776. this.properties = [];
  777. this.type;
  778. var requiredFields = definition.enum || [];
  779. this.type = typeFromJsonSchema(definition.type, definition.format);
  780. }
  781. PrimitiveModel.prototype.createJSONSample = function(modelsToIgnore) {
  782. var result = this.type;
  783. return result;
  784. };
  785. PrimitiveModel.prototype.getSampleValue = function() {
  786. var result = this.type;
  787. return null;
  788. }
  789. PrimitiveModel.prototype.getMockSignature = function(modelsToIgnore) {
  790. var propertiesStr = [];
  791. var i;
  792. for (i = 0; i < this.properties.length; i++) {
  793. var prop = this.properties[i];
  794. propertiesStr.push(prop.toString());
  795. }
  796. var strong = '<span class="strong">';
  797. var stronger = '<span class="stronger">';
  798. var strongClose = '</span>';
  799. var classOpen = strong + this.name + ' {' + strongClose;
  800. var classClose = strong + '}' + strongClose;
  801. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  802. if (!modelsToIgnore)
  803. modelsToIgnore = [];
  804. modelsToIgnore.push(this.name);
  805. var i;
  806. for (i = 0; i < this.properties.length; i++) {
  807. var prop = this.properties[i];
  808. var ref = prop['$ref'];
  809. var model = models[ref];
  810. if (model && modelsToIgnore.indexOf(ref) === -1) {
  811. returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
  812. }
  813. }
  814. return returnVal;
  815. };
  816. var Model = function(name, definition) {
  817. this.name = name;
  818. this.definition = definition || {};
  819. this.properties = [];
  820. var requiredFields = definition.enum || [];
  821. var key;
  822. var props = definition.properties;
  823. if(props) {
  824. for(key in props) {
  825. var required = false;
  826. var property = props[key];
  827. if(requiredFields.indexOf(key) >= 0)
  828. required = true;
  829. this.properties.push(new Property(key, property, required));
  830. }
  831. }
  832. }
  833. Model.prototype.createJSONSample = function(modelsToIgnore) {
  834. var result = {};
  835. var modelsToIgnore = (modelsToIgnore||[])
  836. modelsToIgnore.push(this.name);
  837. for (var i = 0; i < this.properties.length; i++) {
  838. prop = this.properties[i];
  839. result[prop.name] = prop.getSampleValue(modelsToIgnore);
  840. }
  841. modelsToIgnore.pop(this.name);
  842. return result;
  843. };
  844. Model.prototype.getSampleValue = function() {
  845. var i;
  846. var obj = {};
  847. for(i = 0; i < this.properties.length; i++ ) {
  848. var property = this.properties[i];
  849. obj[property.name] = property.sampleValue();
  850. }
  851. return obj;
  852. }
  853. Model.prototype.getMockSignature = function(modelsToIgnore) {
  854. var propertiesStr = [];
  855. var i;
  856. for (i = 0; i < this.properties.length; i++) {
  857. var prop = this.properties[i];
  858. propertiesStr.push(prop.toString());
  859. }
  860. var strong = '<span class="strong">';
  861. var stronger = '<span class="stronger">';
  862. var strongClose = '</span>';
  863. var classOpen = strong + this.name + ' {' + strongClose;
  864. var classClose = strong + '}' + strongClose;
  865. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  866. if (!modelsToIgnore)
  867. modelsToIgnore = [];
  868. modelsToIgnore.push(this.name);
  869. var i;
  870. for (i = 0; i < this.properties.length; i++) {
  871. var prop = this.properties[i];
  872. var ref = prop['$ref'];
  873. var model = models[ref];
  874. if (model && modelsToIgnore.indexOf(ref) === -1) {
  875. returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
  876. }
  877. }
  878. return returnVal;
  879. };
  880. var Property = function(name, obj, required) {
  881. this.schema = obj;
  882. this.required = required;
  883. if(obj['$ref']) {
  884. var refType = obj['$ref'];
  885. refType = refType.indexOf('#/definitions') === -1 ? refType : refType.substring('#/definitions').length;
  886. this['$ref'] = refType;
  887. }
  888. else if (obj.type === 'array') {
  889. if(obj.items['$ref'])
  890. this['$ref'] = obj.items['$ref'];
  891. else
  892. obj = obj.items;
  893. }
  894. this.name = name;
  895. this.obj = obj;
  896. this.optional = true;
  897. this.example = obj.example || null;
  898. }
  899. Property.prototype.getSampleValue = function () {
  900. return this.sampleValue(false);
  901. }
  902. Property.prototype.isArray = function () {
  903. var schema = this.schema;
  904. if(schema.type === 'array')
  905. return true;
  906. else
  907. return false;
  908. }
  909. Property.prototype.sampleValue = function(isArray, ignoredModels) {
  910. isArray = (isArray || this.isArray());
  911. ignoredModels = (ignoredModels || {})
  912. var type = getStringSignature(this.obj);
  913. var output;
  914. if(this['$ref']) {
  915. var refModel = models[this['$ref']];
  916. if(refModel && typeof ignoredModels[refModel] === 'undefined') {
  917. output = refModel.getSampleValue(ignoredModels);
  918. }
  919. else
  920. type = refModel;
  921. }
  922. else if(this.example)
  923. output = this.example;
  924. else if(type === 'date-time') {
  925. output = new Date().toISOString();
  926. }
  927. else if(type === 'string') {
  928. output = 'string';
  929. }
  930. else if(type === 'integer') {
  931. output = 0;
  932. }
  933. else if(type === 'long') {
  934. output = 0;
  935. }
  936. else if(type === 'float') {
  937. output = 0.0;
  938. }
  939. else if(type === 'double') {
  940. output = 0.0;
  941. }
  942. else if(type === 'boolean') {
  943. output = true;
  944. }
  945. else
  946. output = {};
  947. if(isArray) return [output];
  948. else return output;
  949. }
  950. getStringSignature = function(obj) {
  951. var str = '';
  952. if(obj.type === 'array') {
  953. obj = (obj.items || obj['$ref'] || {});
  954. str += 'Array[';
  955. }
  956. if(obj.type === 'integer' && obj.format === 'int32')
  957. str += 'integer';
  958. else if(obj.type === 'integer' && obj.format === 'int64')
  959. str += 'long';
  960. else if(obj.type === 'string' && obj.format === 'date-time')
  961. str += 'date-time';
  962. else if(obj.type === 'string' && obj.format === 'date')
  963. str += 'date';
  964. else if(obj.type === 'number' && obj.format === 'float')
  965. str += 'float';
  966. else if(obj.type === 'number' && obj.format === 'double')
  967. str += 'double';
  968. else if(obj.type === 'boolean')
  969. str += 'boolean';
  970. else
  971. str += obj.type || obj['$ref'];
  972. if(obj.type === 'array')
  973. str += ']';
  974. return str;
  975. }
  976. simpleRef = function(name) {
  977. if(name.indexOf("#/definitions/") === 0)
  978. return name.substring('#/definitions/'.length)
  979. else
  980. return name;
  981. }
  982. Property.prototype.toString = function() {
  983. var str = getStringSignature(this.obj);
  984. if(str !== '')
  985. str = this.name + ' : ' + str;
  986. else
  987. str = this.name + ' : ' + JSON.stringify(this.obj);
  988. if(!this.required)
  989. str += ' (optional)';
  990. return str;
  991. }
  992. typeFromJsonSchema = function(type, format) {
  993. var str;
  994. if(type === 'integer' && format === 'int32')
  995. str = 'integer';
  996. else if(type === 'integer' && format === 'int64')
  997. str = 'long';
  998. else if(type === 'string' && format === 'date-time')
  999. str = 'date-time';
  1000. else if(type === 'string' && format === 'date')
  1001. str = 'date';
  1002. else if(type === 'number' && format === 'float')
  1003. str = 'float';
  1004. else if(type === 'number' && format === 'double')
  1005. str = 'double';
  1006. else if(type === 'boolean')
  1007. str = 'boolean';
  1008. else if(type === 'string')
  1009. str = 'string';
  1010. return str;
  1011. }
  1012. var e = (typeof window !== 'undefined' ? window : exports);
  1013. var sampleModels = {};
  1014. var cookies = {};
  1015. var models = {};
  1016. e.authorizations = new SwaggerAuthorizations();
  1017. e.ApiKeyAuthorization = ApiKeyAuthorization;
  1018. e.PasswordAuthorization = PasswordAuthorization;
  1019. e.CookieAuthorization = CookieAuthorization;
  1020. e.SwaggerClient = SwaggerClient;/**
  1021. * SwaggerHttp is a wrapper for executing requests
  1022. */
  1023. var SwaggerHttp = function() {};
  1024. SwaggerHttp.prototype.execute = function(obj) {
  1025. if(obj && (typeof obj.useJQuery === 'boolean'))
  1026. this.useJQuery = obj.useJQuery;
  1027. else
  1028. this.useJQuery = this.isIE8();
  1029. if(this.useJQuery)
  1030. return new JQueryHttpClient().execute(obj);
  1031. else
  1032. return new ShredHttpClient().execute(obj);
  1033. }
  1034. SwaggerHttp.prototype.isIE8 = function() {
  1035. var detectedIE = false;
  1036. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1037. nav = navigator.userAgent.toLowerCase();
  1038. if (nav.indexOf('msie') !== -1) {
  1039. var version = parseInt(nav.split('msie')[1]);
  1040. if (version <= 8) {
  1041. detectedIE = true;
  1042. }
  1043. }
  1044. }
  1045. return detectedIE;
  1046. };
  1047. /*
  1048. * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic.
  1049. * NOTE: when jQuery is available it will export both '$' and 'jQuery' to the global space.
  1050. * Since we are using closures here we need to alias it for internal use.
  1051. */
  1052. var JQueryHttpClient = function(options) {
  1053. "use strict";
  1054. if(!jQuery){
  1055. var jQuery = window.jQuery;
  1056. }
  1057. }
  1058. JQueryHttpClient.prototype.execute = function(obj) {
  1059. var cb = obj.on;
  1060. var request = obj;
  1061. obj.type = obj.method;
  1062. obj.cache = false;
  1063. obj.beforeSend = function(xhr) {
  1064. var key, results;
  1065. if (obj.headers) {
  1066. results = [];
  1067. var key;
  1068. for (key in obj.headers) {
  1069. if (key.toLowerCase() === "content-type") {
  1070. results.push(obj.contentType = obj.headers[key]);
  1071. } else if (key.toLowerCase() === "accept") {
  1072. results.push(obj.accepts = obj.headers[key]);
  1073. } else {
  1074. results.push(xhr.setRequestHeader(key, obj.headers[key]));
  1075. }
  1076. }
  1077. return results;
  1078. }
  1079. };
  1080. obj.data = obj.body;
  1081. obj.complete = function(response, textStatus, opts) {
  1082. var headers = {},
  1083. headerArray = response.getAllResponseHeaders().split("\n");
  1084. for(var i = 0; i < headerArray.length; i++) {
  1085. var toSplit = headerArray[i].trim();
  1086. if(toSplit.length === 0)
  1087. continue;
  1088. var separator = toSplit.indexOf(":");
  1089. if(separator === -1) {
  1090. // Name but no value in the header
  1091. headers[toSplit] = null;
  1092. continue;
  1093. }
  1094. var name = toSplit.substring(0, separator).trim(),
  1095. value = toSplit.substring(separator + 1).trim();
  1096. headers[name] = value;
  1097. }
  1098. var out = {
  1099. url: request.url,
  1100. method: request.method,
  1101. status: response.status,
  1102. data: response.responseText,
  1103. headers: headers
  1104. };
  1105. var contentType = (headers["content-type"]||headers["Content-Type"]||null)
  1106. if(contentType != null) {
  1107. if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
  1108. if(response.responseText && response.responseText !== "")
  1109. out.obj = JSON.parse(response.responseText);
  1110. else
  1111. out.obj = {}
  1112. }
  1113. }
  1114. if(response.status >= 200 && response.status < 300)
  1115. cb.response(out);
  1116. else if(response.status === 0 || (response.status >= 400 && response.status < 599))
  1117. cb.error(out);
  1118. else
  1119. return cb.response(out);
  1120. };
  1121. jQuery.support.cors = true;
  1122. return jQuery.ajax(obj);
  1123. }
  1124. /*
  1125. * ShredHttpClient is a light-weight, node or browser HTTP client
  1126. */
  1127. var ShredHttpClient = function(options) {
  1128. this.options = (options||{});
  1129. this.isInitialized = false;
  1130. var identity, toString;
  1131. if (typeof window !== 'undefined') {
  1132. this.Shred = require("./shred");
  1133. this.content = require("./shred/content");
  1134. }
  1135. else
  1136. this.Shred = require("shred");
  1137. this.shred = new this.Shred();
  1138. }
  1139. ShredHttpClient.prototype.initShred = function () {
  1140. this.isInitialized = true;
  1141. this.registerProcessors(this.shred);
  1142. }
  1143. ShredHttpClient.prototype.registerProcessors = function(shred) {
  1144. var identity = function(x) {
  1145. return x;
  1146. };
  1147. var toString = function(x) {
  1148. return x.toString();
  1149. };
  1150. if (typeof window !== 'undefined') {
  1151. this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
  1152. parser: identity,
  1153. stringify: toString
  1154. });
  1155. } else {
  1156. this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
  1157. parser: identity,
  1158. stringify: toString
  1159. });
  1160. }
  1161. }
  1162. ShredHttpClient.prototype.execute = function(obj) {
  1163. if(!this.isInitialized)
  1164. this.initShred();
  1165. var cb = obj.on, res;
  1166. var transform = function(response) {
  1167. var out = {
  1168. headers: response._headers,
  1169. url: response.request.url,
  1170. method: response.request.method,
  1171. status: response.status,
  1172. data: response.content.data
  1173. };
  1174. var contentType = (response._headers["content-type"]||response._headers["Content-Type"]||null)
  1175. if(contentType != null) {
  1176. if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
  1177. if(response.content.data && response.content.data !== "")
  1178. out.obj = JSON.parse(response.content.data);
  1179. else
  1180. out.obj = {}
  1181. }
  1182. }
  1183. return out;
  1184. };
  1185. res = {
  1186. error: function(response) {
  1187. if (obj)
  1188. return cb.error(transform(response));
  1189. },
  1190. redirect: function(response) {
  1191. if (obj)
  1192. return cb.redirect(transform(response));
  1193. },
  1194. 307: function(response) {
  1195. if (obj)
  1196. return cb.redirect(transform(response));
  1197. },
  1198. response: function(response) {
  1199. if (obj)
  1200. return cb.response(transform(response));
  1201. }
  1202. };
  1203. if (obj) {
  1204. obj.on = res;
  1205. }
  1206. return this.shred.request(obj);
  1207. };