Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

2909 rindas
84 KiB

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