Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

2975 rader
86 KiB

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