Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

1654 linhas
48 KiB

  1. // swagger.js
  2. // version 2.0.39
  3. var __bind = function(fn, me){
  4. return function(){
  5. return fn.apply(me, arguments);
  6. };
  7. };
  8. log = function(){
  9. log.history = log.history || [];
  10. log.history.push(arguments);
  11. if(this.console){
  12. console.log( Array.prototype.slice.call(arguments)[0] );
  13. }
  14. };
  15. // if you want to apply conditional formatting of parameter values
  16. parameterMacro = function(value) {
  17. return value;
  18. }
  19. // if you want to apply conditional formatting of model property values
  20. modelPropertyMacro = function(value) {
  21. return value;
  22. }
  23. if (!Array.prototype.indexOf) {
  24. Array.prototype.indexOf = function(obj, start) {
  25. for (var i = (start || 0), j = this.length; i < j; i++) {
  26. if (this[i] === obj) { return i; }
  27. }
  28. return -1;
  29. }
  30. }
  31. if (!('filter' in Array.prototype)) {
  32. Array.prototype.filter= function(filter, that /*opt*/) {
  33. var other= [], v;
  34. for (var i=0, n= this.length; i<n; i++)
  35. if (i in this && filter.call(that, v= this[i], i, this))
  36. other.push(v);
  37. return other;
  38. };
  39. }
  40. if (!('map' in Array.prototype)) {
  41. Array.prototype.map= function(mapper, that /*opt*/) {
  42. var other= new Array(this.length);
  43. for (var i= 0, n= this.length; i<n; i++)
  44. if (i in this)
  45. other[i]= mapper.call(that, this[i], i, this);
  46. return other;
  47. };
  48. }
  49. Object.keys = Object.keys || (function () {
  50. var hasOwnProperty = Object.prototype.hasOwnProperty,
  51. hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
  52. DontEnums = [
  53. 'toString',
  54. 'toLocaleString',
  55. 'valueOf',
  56. 'hasOwnProperty',
  57. 'isPrototypeOf',
  58. 'propertyIsEnumerable',
  59. 'constructor'
  60. ],
  61. DontEnumsLength = DontEnums.length;
  62. return function (o) {
  63. if (typeof o != "object" && typeof o != "function" || o === null)
  64. throw new TypeError("Object.keys called on a non-object");
  65. var result = [];
  66. for (var name in o) {
  67. if (hasOwnProperty.call(o, name))
  68. result.push(name);
  69. }
  70. if (hasDontEnumBug) {
  71. for (var i = 0; i < DontEnumsLength; i++) {
  72. if (hasOwnProperty.call(o, DontEnums[i]))
  73. result.push(DontEnums[i]);
  74. }
  75. }
  76. return result;
  77. };
  78. })();
  79. var SwaggerApi = function(url, options) {
  80. this.isBuilt = false;
  81. this.url = null;
  82. this.debug = false;
  83. this.basePath = null;
  84. this.authorizations = null;
  85. this.authorizationScheme = null;
  86. this.info = null;
  87. this.useJQuery = false;
  88. this.modelsArray = [];
  89. options = (options||{});
  90. if (url)
  91. if (url.url)
  92. options = url;
  93. else
  94. this.url = url;
  95. else
  96. options = url;
  97. if (options.url != null)
  98. this.url = options.url;
  99. if (options.success != null)
  100. this.success = options.success;
  101. if (typeof options.useJQuery === 'boolean')
  102. this.useJQuery = options.useJQuery;
  103. this.failure = options.failure != null ? options.failure : function() {};
  104. this.progress = options.progress != null ? options.progress : function() {};
  105. if (options.success != null) {
  106. this.build();
  107. this.isBuilt = true;
  108. }
  109. }
  110. SwaggerApi.prototype.build = function() {
  111. if(this.isBuilt)
  112. return this;
  113. var _this = this;
  114. this.progress('fetching resource list: ' + this.url);
  115. var obj = {
  116. useJQuery: this.useJQuery,
  117. url: this.url,
  118. method: "get",
  119. headers: {
  120. accept: "application/json,application/json;charset=\"utf-8\",*/*"
  121. },
  122. on: {
  123. error: function(response) {
  124. if (_this.url.substring(0, 4) !== 'http') {
  125. return _this.fail('Please specify the protocol for ' + _this.url);
  126. } else if (response.status === 0) {
  127. return _this.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.');
  128. } else if (response.status === 404) {
  129. return _this.fail('Can\'t read swagger JSON from ' + _this.url);
  130. } else {
  131. return _this.fail(response.status + ' : ' + response.statusText + ' ' + _this.url);
  132. }
  133. },
  134. response: function(resp) {
  135. var responseObj = resp.obj || JSON.parse(resp.data);
  136. _this.swaggerVersion = responseObj.swaggerVersion;
  137. if (_this.swaggerVersion === "1.2") {
  138. return _this.buildFromSpec(responseObj);
  139. } else {
  140. return _this.buildFrom1_1Spec(responseObj);
  141. }
  142. }
  143. }
  144. };
  145. var e = (typeof window !== 'undefined' ? window : exports);
  146. e.authorizations.apply(obj);
  147. new SwaggerHttp().execute(obj);
  148. return this;
  149. };
  150. SwaggerApi.prototype.buildFromSpec = function(response) {
  151. if (response.apiVersion != null) {
  152. this.apiVersion = response.apiVersion;
  153. }
  154. this.apis = {};
  155. this.apisArray = [];
  156. this.consumes = response.consumes;
  157. this.produces = response.produces;
  158. this.authSchemes = response.authorizations;
  159. if (response.info != null) {
  160. this.info = response.info;
  161. }
  162. var isApi = false;
  163. var i;
  164. for (i = 0; i < response.apis.length; i++) {
  165. var api = response.apis[i];
  166. if (api.operations) {
  167. var j;
  168. for (j = 0; j < api.operations.length; j++) {
  169. operation = api.operations[j];
  170. isApi = true;
  171. }
  172. }
  173. }
  174. if (response.basePath)
  175. this.basePath = response.basePath;
  176. else if (this.url.indexOf('?') > 0)
  177. this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
  178. else
  179. this.basePath = this.url;
  180. if (isApi) {
  181. var newName = response.resourcePath.replace(/\//g, '');
  182. this.resourcePath = response.resourcePath;
  183. res = new SwaggerResource(response, this);
  184. this.apis[newName] = res;
  185. this.apisArray.push(res);
  186. } else {
  187. var k;
  188. for (k = 0; k < response.apis.length; k++) {
  189. var resource = response.apis[k];
  190. res = new SwaggerResource(resource, this);
  191. this.apis[res.name] = res;
  192. this.apisArray.push(res);
  193. }
  194. }
  195. if (this.success) {
  196. this.success();
  197. }
  198. return this;
  199. };
  200. SwaggerApi.prototype.buildFrom1_1Spec = function(response) {
  201. log("This API is using a deprecated version of Swagger! Please see http://github.com/wordnik/swagger-core/wiki for more info");
  202. if (response.apiVersion != null)
  203. this.apiVersion = response.apiVersion;
  204. this.apis = {};
  205. this.apisArray = [];
  206. this.produces = response.produces;
  207. if (response.info != null) {
  208. this.info = response.info;
  209. }
  210. var isApi = false;
  211. for (var i = 0; i < response.apis.length; i++) {
  212. var api = response.apis[i];
  213. if (api.operations) {
  214. for (var j = 0; j < api.operations.length; j++) {
  215. operation = api.operations[j];
  216. isApi = true;
  217. }
  218. }
  219. }
  220. if (response.basePath) {
  221. this.basePath = response.basePath;
  222. } else if (this.url.indexOf('?') > 0) {
  223. this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
  224. } else {
  225. this.basePath = this.url;
  226. }
  227. if (isApi) {
  228. var newName = response.resourcePath.replace(/\//g, '');
  229. this.resourcePath = response.resourcePath;
  230. var res = new SwaggerResource(response, this);
  231. this.apis[newName] = res;
  232. this.apisArray.push(res);
  233. } else {
  234. for (k = 0; k < response.apis.length; k++) {
  235. resource = response.apis[k];
  236. res = new SwaggerResource(resource, this);
  237. this.apis[res.name] = res;
  238. this.apisArray.push(res);
  239. }
  240. }
  241. if (this.success) {
  242. this.success();
  243. }
  244. return this;
  245. };
  246. SwaggerApi.prototype.selfReflect = function() {
  247. var resource, resource_name, _ref;
  248. if (this.apis == null) {
  249. return false;
  250. }
  251. _ref = this.apis;
  252. for (resource_name in _ref) {
  253. resource = _ref[resource_name];
  254. if (resource.ready == null) {
  255. return false;
  256. }
  257. }
  258. this.setConsolidatedModels();
  259. this.ready = true;
  260. if (this.success != null) {
  261. return this.success();
  262. }
  263. };
  264. SwaggerApi.prototype.fail = function(message) {
  265. this.failure(message);
  266. throw message;
  267. };
  268. SwaggerApi.prototype.setConsolidatedModels = function() {
  269. var model, modelName, resource, resource_name, _i, _len, _ref, _ref1, _results;
  270. this.models = {};
  271. _ref = this.apis;
  272. for (resource_name in _ref) {
  273. resource = _ref[resource_name];
  274. for (modelName in resource.models) {
  275. if (this.models[modelName] == null) {
  276. this.models[modelName] = resource.models[modelName];
  277. this.modelsArray.push(resource.models[modelName]);
  278. }
  279. }
  280. }
  281. _ref1 = this.modelsArray;
  282. _results = [];
  283. for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
  284. model = _ref1[_i];
  285. _results.push(model.setReferencedModels(this.models));
  286. }
  287. return _results;
  288. };
  289. SwaggerApi.prototype.help = function() {
  290. var operation, operation_name, parameter, resource, resource_name, _i, _len, _ref, _ref1, _ref2;
  291. _ref = this.apis;
  292. for (resource_name in _ref) {
  293. resource = _ref[resource_name];
  294. log(resource_name);
  295. _ref1 = resource.operations;
  296. for (operation_name in _ref1) {
  297. operation = _ref1[operation_name];
  298. log(" " + operation.nickname);
  299. _ref2 = operation.parameters;
  300. for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
  301. parameter = _ref2[_i];
  302. log(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description);
  303. }
  304. }
  305. }
  306. return this;
  307. };
  308. var SwaggerResource = function(resourceObj, api) {
  309. var _this = this;
  310. this.api = api;
  311. this.api = this.api;
  312. consumes = (this.consumes | []);
  313. produces = (this.produces | []);
  314. this.path = this.api.resourcePath != null ? this.api.resourcePath : resourceObj.path;
  315. this.description = resourceObj.description;
  316. var parts = this.path.split("/");
  317. this.name = parts[parts.length - 1].replace('.{format}', '');
  318. this.basePath = this.api.basePath;
  319. this.operations = {};
  320. this.operationsArray = [];
  321. this.modelsArray = [];
  322. this.models = {};
  323. this.rawModels = {};
  324. this.useJQuery = (typeof api.useJQuery !== 'undefined' ? api.useJQuery : null);
  325. if ((resourceObj.apis != null) && (this.api.resourcePath != null)) {
  326. this.addApiDeclaration(resourceObj);
  327. } else {
  328. if (this.path == null) {
  329. this.api.fail("SwaggerResources must have a path.");
  330. }
  331. if (this.path.substring(0, 4) === 'http') {
  332. this.url = this.path.replace('{format}', 'json');
  333. } else {
  334. this.url = this.api.basePath + this.path.replace('{format}', 'json');
  335. }
  336. this.api.progress('fetching resource ' + this.name + ': ' + this.url);
  337. obj = {
  338. url: this.url,
  339. method: "get",
  340. useJQuery: this.useJQuery,
  341. headers: {
  342. accept: "application/json,application/json;charset=\"utf-8\",*/*"
  343. },
  344. on: {
  345. response: function(resp) {
  346. var responseObj = resp.obj || JSON.parse(resp.data);
  347. return _this.addApiDeclaration(responseObj);
  348. },
  349. error: function(response) {
  350. return _this.api.fail("Unable to read api '" +
  351. _this.name + "' from path " + _this.url + " (server returned " + response.statusText + ")");
  352. }
  353. }
  354. };
  355. var e = typeof window !== 'undefined' ? window : exports;
  356. e.authorizations.apply(obj);
  357. new SwaggerHttp().execute(obj);
  358. }
  359. }
  360. SwaggerResource.prototype.getAbsoluteBasePath = function (relativeBasePath) {
  361. var pos, url;
  362. url = this.api.basePath;
  363. pos = url.lastIndexOf(relativeBasePath);
  364. var parts = url.split("/");
  365. var rootUrl = parts[0] + "//" + parts[2];
  366. if(relativeBasePath.indexOf("http") === 0)
  367. return relativeBasePath;
  368. if(relativeBasePath === "/")
  369. return rootUrl;
  370. if(relativeBasePath.substring(0, 1) == "/") {
  371. // use root + relative
  372. return rootUrl + relativeBasePath;
  373. }
  374. else {
  375. var pos = this.basePath.lastIndexOf("/");
  376. var base = this.basePath.substring(0, pos);
  377. if(base.substring(base.length - 1) == "/")
  378. return base + relativeBasePath;
  379. else
  380. return base + "/" + relativeBasePath;
  381. }
  382. };
  383. SwaggerResource.prototype.addApiDeclaration = function(response) {
  384. if (response.produces != null)
  385. this.produces = response.produces;
  386. if (response.consumes != null)
  387. this.consumes = response.consumes;
  388. if ((response.basePath != null) && response.basePath.replace(/\s/g, '').length > 0)
  389. this.basePath = response.basePath.indexOf("http") === -1 ? this.getAbsoluteBasePath(response.basePath) : response.basePath;
  390. this.addModels(response.models);
  391. if (response.apis) {
  392. for (var i = 0 ; i < response.apis.length; i++) {
  393. var endpoint = response.apis[i];
  394. this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces);
  395. }
  396. }
  397. this.api[this.name] = this;
  398. this.ready = true;
  399. return this.api.selfReflect();
  400. };
  401. SwaggerResource.prototype.addModels = function(models) {
  402. if (models != null) {
  403. var modelName;
  404. for (modelName in models) {
  405. if (this.models[modelName] == null) {
  406. var swaggerModel = new SwaggerModel(modelName, models[modelName]);
  407. this.modelsArray.push(swaggerModel);
  408. this.models[modelName] = swaggerModel;
  409. this.rawModels[modelName] = models[modelName];
  410. }
  411. }
  412. var output = [];
  413. for (var i = 0; i < this.modelsArray.length; i++) {
  414. model = this.modelsArray[i];
  415. output.push(model.setReferencedModels(this.models));
  416. }
  417. return output;
  418. }
  419. };
  420. SwaggerResource.prototype.addOperations = function(resource_path, ops, consumes, produces) {
  421. if (ops) {
  422. output = [];
  423. for (var i = 0; i < ops.length; i++) {
  424. o = ops[i];
  425. consumes = this.consumes;
  426. produces = this.produces;
  427. if (o.consumes != null)
  428. consumes = o.consumes;
  429. else
  430. consumes = this.consumes;
  431. if (o.produces != null)
  432. produces = o.produces;
  433. else
  434. produces = this.produces;
  435. type = (o.type||o.responseClass);
  436. if (type === "array") {
  437. ref = null;
  438. if (o.items)
  439. ref = o.items["type"] || o.items["$ref"];
  440. type = "array[" + ref + "]";
  441. }
  442. responseMessages = o.responseMessages;
  443. method = o.method;
  444. if (o.httpMethod) {
  445. method = o.httpMethod;
  446. }
  447. if (o.supportedContentTypes) {
  448. consumes = o.supportedContentTypes;
  449. }
  450. if (o.errorResponses) {
  451. responseMessages = o.errorResponses;
  452. for (var j = 0; j < responseMessages.length; j++) {
  453. r = responseMessages[j];
  454. r.message = r.reason;
  455. r.reason = null;
  456. }
  457. }
  458. o.nickname = this.sanitize(o.nickname);
  459. op = new SwaggerOperation(o.nickname, resource_path, method, o.parameters, o.summary, o.notes, type, responseMessages, this, consumes, produces, o.authorizations);
  460. this.operations[op.nickname] = op;
  461. output.push(this.operationsArray.push(op));
  462. }
  463. return output;
  464. }
  465. };
  466. SwaggerResource.prototype.sanitize = function(nickname) {
  467. var op;
  468. op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|.\/?,\\'""-]/g, '_');
  469. op = op.replace(/((_){2,})/g, '_');
  470. op = op.replace(/^(_)*/g, '');
  471. op = op.replace(/([_])*$/g, '');
  472. return op;
  473. };
  474. SwaggerResource.prototype.help = function() {
  475. var op = this.operations;
  476. var output = [];
  477. var operation_name;
  478. for (operation_name in op) {
  479. operation = op[operation_name];
  480. var msg = " " + operation.nickname;
  481. for (var i = 0; i < operation.parameters; i++) {
  482. parameter = operation.parameters[i];
  483. msg.concat(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description);
  484. }
  485. output.push(msg);
  486. }
  487. return output;
  488. };
  489. var SwaggerModel = function(modelName, obj) {
  490. this.name = obj.id != null ? obj.id : modelName;
  491. this.properties = [];
  492. var propertyName;
  493. for (propertyName in obj.properties) {
  494. if (obj.required != null) {
  495. var value;
  496. for (value in obj.required) {
  497. if (propertyName === obj.required[value]) {
  498. obj.properties[propertyName].required = true;
  499. }
  500. }
  501. }
  502. prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName]);
  503. this.properties.push(prop);
  504. }
  505. }
  506. SwaggerModel.prototype.setReferencedModels = function(allModels) {
  507. var results = [];
  508. for (var i = 0; i < this.properties.length; i++) {
  509. var property = this.properties[i];
  510. var type = property.type || property.dataType;
  511. if (allModels[type] != null)
  512. results.push(property.refModel = allModels[type]);
  513. else if ((property.refDataType != null) && (allModels[property.refDataType] != null))
  514. results.push(property.refModel = allModels[property.refDataType]);
  515. else
  516. results.push(void 0);
  517. }
  518. return results;
  519. };
  520. SwaggerModel.prototype.getMockSignature = function(modelsToIgnore) {
  521. var propertiesStr = [];
  522. for (var i = 0; i < this.properties.length; i++) {
  523. prop = this.properties[i];
  524. propertiesStr.push(prop.toString());
  525. }
  526. var strong = '<span class="strong">';
  527. var stronger = '<span class="stronger">';
  528. var strongClose = '</span>';
  529. var classOpen = strong + this.name + ' {' + strongClose;
  530. var classClose = strong + '}' + strongClose;
  531. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  532. if (!modelsToIgnore)
  533. modelsToIgnore = [];
  534. modelsToIgnore.push(this.name);
  535. for (var i = 0; i < this.properties.length; i++) {
  536. prop = this.properties[i];
  537. if ((prop.refModel != null) && modelsToIgnore.indexOf(prop.refModel.name) === -1) {
  538. returnVal = returnVal + ('<br>' + prop.refModel.getMockSignature(modelsToIgnore));
  539. }
  540. }
  541. return returnVal;
  542. };
  543. SwaggerModel.prototype.createJSONSample = function(modelsToIgnore) {
  544. if(sampleModels[this.name]) {
  545. return sampleModels[this.name];
  546. }
  547. else {
  548. var result = {};
  549. var modelsToIgnore = (modelsToIgnore||[])
  550. modelsToIgnore.push(this.name);
  551. for (var i = 0; i < this.properties.length; i++) {
  552. prop = this.properties[i];
  553. result[prop.name] = prop.getSampleValue(modelsToIgnore);
  554. }
  555. modelsToIgnore.pop(this.name);
  556. return result;
  557. }
  558. };
  559. var SwaggerModelProperty = function(name, obj) {
  560. this.name = name;
  561. this.dataType = obj.type || obj.dataType || obj["$ref"];
  562. this.isCollection = this.dataType && (this.dataType.toLowerCase() === 'array' || this.dataType.toLowerCase() === 'list' || this.dataType.toLowerCase() === 'set');
  563. this.descr = obj.description;
  564. this.required = obj.required;
  565. this.defaultValue = modelPropertyMacro(obj.defaultValue);
  566. if (obj.items != null) {
  567. if (obj.items.type != null) {
  568. this.refDataType = obj.items.type;
  569. }
  570. if (obj.items.$ref != null) {
  571. this.refDataType = obj.items.$ref;
  572. }
  573. }
  574. this.dataTypeWithRef = this.refDataType != null ? (this.dataType + '[' + this.refDataType + ']') : this.dataType;
  575. if (obj.allowableValues != null) {
  576. this.valueType = obj.allowableValues.valueType;
  577. this.values = obj.allowableValues.values;
  578. if (this.values != null) {
  579. this.valuesString = "'" + this.values.join("' or '") + "'";
  580. }
  581. }
  582. if (obj["enum"] != null) {
  583. this.valueType = "string";
  584. this.values = obj["enum"];
  585. if (this.values != null) {
  586. this.valueString = "'" + this.values.join("' or '") + "'";
  587. }
  588. }
  589. }
  590. SwaggerModelProperty.prototype.getSampleValue = function(modelsToIgnore) {
  591. var result;
  592. if ((this.refModel != null) && (modelsToIgnore.indexOf(prop.refModel.name) === -1)) {
  593. result = this.refModel.createJSONSample(modelsToIgnore);
  594. } else {
  595. if (this.isCollection) {
  596. result = this.toSampleValue(this.refDataType);
  597. } else {
  598. result = this.toSampleValue(this.dataType);
  599. }
  600. }
  601. if (this.isCollection) {
  602. return [result];
  603. } else {
  604. return result;
  605. }
  606. };
  607. SwaggerModelProperty.prototype.toSampleValue = function(value) {
  608. var result;
  609. if ((typeof this.defaultValue !== 'undefined') && this.defaultValue !== null) {
  610. result = this.defaultValue;
  611. } else if (value === "integer") {
  612. result = 0;
  613. } else if (value === "boolean") {
  614. result = false;
  615. } else if (value === "double" || value === "number") {
  616. result = 0.0;
  617. } else if (value === "string") {
  618. result = "";
  619. } else {
  620. result = value;
  621. }
  622. return result;
  623. };
  624. SwaggerModelProperty.prototype.toString = function() {
  625. var req = this.required ? 'propReq' : 'propOpt';
  626. var str = '<span class="propName ' + req + '">' + this.name + '</span> (<span class="propType">' + this.dataTypeWithRef + '</span>';
  627. if (!this.required) {
  628. str += ', <span class="propOptKey">optional</span>';
  629. }
  630. str += ')';
  631. if (this.values != null) {
  632. str += " = <span class='propVals'>['" + this.values.join("' or '") + "']</span>";
  633. }
  634. if (this.descr != null) {
  635. str += ': <span class="propDesc">' + this.descr + '</span>';
  636. }
  637. return str;
  638. };
  639. var SwaggerOperation = function(nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations) {
  640. var _this = this;
  641. var errors = [];
  642. this.nickname = (nickname||errors.push("SwaggerOperations must have a nickname."));
  643. this.path = (path||errors.push("SwaggerOperation " + nickname + " is missing path."));
  644. this.method = (method||errors.push("SwaggerOperation " + nickname + " is missing method."));
  645. this.parameters = parameters != null ? parameters : [];
  646. this.summary = summary;
  647. this.notes = notes;
  648. this.type = type;
  649. this.responseMessages = (responseMessages||[]);
  650. this.resource = (resource||errors.push("Resource is required"));
  651. this.consumes = consumes;
  652. this.produces = produces;
  653. this.authorizations = authorizations;
  654. this["do"] = __bind(this["do"], this);
  655. if (errors.length > 0)
  656. this.resource.api.fail(errors);
  657. this.path = this.path.replace('{format}', 'json');
  658. this.method = this.method.toLowerCase();
  659. this.isGetMethod = this.method === "get";
  660. this.resourceName = this.resource.name;
  661. if(typeof this.type !== 'undefined' && this.type === 'void')
  662. this.type = null;
  663. else {
  664. this.responseClassSignature = this.getSignature(this.type, this.resource.models);
  665. this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models);
  666. }
  667. for(var i = 0; i < this.parameters.length; i ++) {
  668. var param = this.parameters[i];
  669. // might take this away
  670. param.name = param.name || param.type || param.dataType;
  671. // for 1.1 compatibility
  672. var type = param.type || param.dataType;
  673. if(type === 'array') {
  674. type = 'array[' + (param.items.$ref ? param.items.$ref : param.items.type) + ']';
  675. }
  676. param.type = type;
  677. if(type.toLowerCase() === 'boolean') {
  678. param.allowableValues = {};
  679. param.allowableValues.values = ["true", "false"];
  680. }
  681. param.signature = this.getSignature(type, this.resource.models);
  682. param.sampleJSON = this.getSampleJSON(type, this.resource.models);
  683. var enumValue = param["enum"];
  684. if(enumValue != null) {
  685. param.isList = true;
  686. param.allowableValues = {};
  687. param.allowableValues.descriptiveValues = [];
  688. for(var j = 0; j < enumValue.length; j++) {
  689. var v = enumValue[j];
  690. if(param.defaultValue != null) {
  691. param.allowableValues.descriptiveValues.push ({
  692. value: String(v),
  693. isDefault: (v === param.defaultValue)
  694. });
  695. }
  696. else {
  697. param.allowableValues.descriptiveValues.push ({
  698. value: String(v),
  699. isDefault: false
  700. });
  701. }
  702. }
  703. }
  704. else if(param.allowableValues != null) {
  705. if(param.allowableValues.valueType === "RANGE")
  706. param.isRange = true;
  707. else
  708. param.isList = true;
  709. if(param.allowableValues != null) {
  710. param.allowableValues.descriptiveValues = [];
  711. if(param.allowableValues.values) {
  712. for(var j = 0; j < param.allowableValues.values.length; j++){
  713. var v = param.allowableValues.values[j];
  714. if(param.defaultValue != null) {
  715. param.allowableValues.descriptiveValues.push ({
  716. value: String(v),
  717. isDefault: (v === param.defaultValue)
  718. });
  719. }
  720. else {
  721. param.allowableValues.descriptiveValues.push ({
  722. value: String(v),
  723. isDefault: false
  724. });
  725. }
  726. }
  727. }
  728. }
  729. }
  730. param.defaultValue = parameterMacro(param.defaultValue);
  731. }
  732. this.resource[this.nickname] = function(args, callback, error) {
  733. return _this["do"](args, callback, error);
  734. };
  735. this.resource[this.nickname].help = function() {
  736. return _this.help();
  737. };
  738. }
  739. SwaggerOperation.prototype.isListType = function(type) {
  740. if (type && type.indexOf('[') >= 0) {
  741. return type.substring(type.indexOf('[') + 1, type.indexOf(']'));
  742. } else {
  743. return void 0;
  744. }
  745. };
  746. SwaggerOperation.prototype.getSignature = function(type, models) {
  747. var isPrimitive, listType;
  748. listType = this.isListType(type);
  749. isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
  750. if (isPrimitive) {
  751. return type;
  752. } else {
  753. if (listType != null) {
  754. return models[listType].getMockSignature();
  755. } else {
  756. return models[type].getMockSignature();
  757. }
  758. }
  759. };
  760. SwaggerOperation.prototype.getSampleJSON = function(type, models) {
  761. var isPrimitive, listType, val;
  762. listType = this.isListType(type);
  763. isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
  764. val = isPrimitive ? void 0 : (listType != null ? models[listType].createJSONSample() : models[type].createJSONSample());
  765. if (val) {
  766. val = listType ? [val] : val;
  767. if(typeof val == "string")
  768. return val;
  769. else if(typeof val === "object") {
  770. var t = val;
  771. if(val instanceof Array && val.length > 0) {
  772. t = val[0];
  773. }
  774. if(t.nodeName) {
  775. var xmlString = new XMLSerializer().serializeToString(t);
  776. return this.formatXml(xmlString);
  777. }
  778. else
  779. return JSON.stringify(val, null, 2);
  780. }
  781. else
  782. return val;
  783. }
  784. };
  785. SwaggerOperation.prototype["do"] = function(args, opts, callback, error) {
  786. var key, param, params, possibleParams, req, requestContentType, responseContentType, value, _i, _len, _ref;
  787. if (args == null) {
  788. args = {};
  789. }
  790. if (opts == null) {
  791. opts = {};
  792. }
  793. requestContentType = null;
  794. responseContentType = null;
  795. if ((typeof args) === "function") {
  796. error = opts;
  797. callback = args;
  798. args = {};
  799. }
  800. if ((typeof opts) === "function") {
  801. error = callback;
  802. callback = opts;
  803. }
  804. if (error == null) {
  805. error = function(xhr, textStatus, error) {
  806. return log(xhr, textStatus, error);
  807. };
  808. }
  809. if (callback == null) {
  810. callback = function(response) {
  811. var content;
  812. content = null;
  813. if (response != null) {
  814. content = response.data;
  815. } else {
  816. content = "no data";
  817. }
  818. return log("default callback: " + content);
  819. };
  820. }
  821. params = {};
  822. params.headers = [];
  823. if (args.headers != null) {
  824. params.headers = args.headers;
  825. delete args.headers;
  826. }
  827. var possibleParams = [];
  828. for(var i = 0; i < this.parameters.length; i++) {
  829. var param = this.parameters[i];
  830. if(param.paramType === 'header') {
  831. if(args[param.name])
  832. params.headers[param.name] = args[param.name];
  833. }
  834. else if(param.paramType === 'form' || param.paramType.toLowerCase() === 'file')
  835. possibleParams.push(param);
  836. }
  837. if (args.body != null) {
  838. params.body = args.body;
  839. delete args.body;
  840. }
  841. if (possibleParams) {
  842. var key;
  843. for (key in possibleParams) {
  844. value = possibleParams[key];
  845. if (args[value.name]) {
  846. params[value.name] = args[value.name];
  847. }
  848. }
  849. }
  850. req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this);
  851. if (opts.mock != null) {
  852. return req;
  853. } else {
  854. return true;
  855. }
  856. };
  857. SwaggerOperation.prototype.pathJson = function() {
  858. return this.path.replace("{format}", "json");
  859. };
  860. SwaggerOperation.prototype.pathXml = function() {
  861. return this.path.replace("{format}", "xml");
  862. };
  863. SwaggerOperation.prototype.encodePathParam = function(pathParam) {
  864. var encParts, part, parts, _i, _len;
  865. pathParam = pathParam.toString();
  866. if (pathParam.indexOf("/") === -1) {
  867. return encodeURIComponent(pathParam);
  868. } else {
  869. parts = pathParam.split("/");
  870. encParts = [];
  871. for (_i = 0, _len = parts.length; _i < _len; _i++) {
  872. part = parts[_i];
  873. encParts.push(encodeURIComponent(part));
  874. }
  875. return encParts.join("/");
  876. }
  877. };
  878. SwaggerOperation.prototype.urlify = function(args) {
  879. var url = this.resource.basePath + this.pathJson();
  880. var params = this.parameters;
  881. for(var i = 0; i < params.length; i ++){
  882. var param = params[i];
  883. if (param.paramType === 'path') {
  884. if(args[param.name]) {
  885. // apply path params and remove from args
  886. var reg = new RegExp('\{' + param.name + '[^\}]*\}', 'gi');
  887. url = url.replace(reg, this.encodePathParam(args[param.name]));
  888. delete args[param.name];
  889. }
  890. else
  891. throw "" + param.name + " is a required path param.";
  892. }
  893. }
  894. var queryParams = "";
  895. for(var i = 0; i < params.length; i ++){
  896. var param = params[i];
  897. if(param.paramType === 'query') {
  898. if (args[param.name] !== undefined) {
  899. if (queryParams !== '')
  900. queryParams += "&";
  901. queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]);
  902. }
  903. }
  904. }
  905. if ((queryParams != null) && queryParams.length > 0)
  906. url += '?' + queryParams;
  907. return url;
  908. };
  909. SwaggerOperation.prototype.supportHeaderParams = function() {
  910. return this.resource.api.supportHeaderParams;
  911. };
  912. SwaggerOperation.prototype.supportedSubmitMethods = function() {
  913. return this.resource.api.supportedSubmitMethods;
  914. };
  915. SwaggerOperation.prototype.getQueryParams = function(args) {
  916. return this.getMatchingParams(['query'], args);
  917. };
  918. SwaggerOperation.prototype.getHeaderParams = function(args) {
  919. return this.getMatchingParams(['header'], args);
  920. };
  921. SwaggerOperation.prototype.getMatchingParams = function(paramTypes, args) {
  922. var matchingParams = {};
  923. var params = this.parameters;
  924. for (var i = 0; i < params.length; i++) {
  925. param = params[i];
  926. if (args && args[param.name])
  927. matchingParams[param.name] = args[param.name];
  928. }
  929. var headers = this.resource.api.headers;
  930. var name;
  931. for (name in headers) {
  932. var value = headers[name];
  933. matchingParams[name] = value;
  934. }
  935. return matchingParams;
  936. };
  937. SwaggerOperation.prototype.help = function() {
  938. var msg = "";
  939. var params = this.parameters;
  940. for (var i = 0; i < params.length; i++) {
  941. var param = params[i];
  942. if (msg !== "")
  943. msg += "\n";
  944. msg += "* " + param.name + (param.required ? ' (required)' : '') + " - " + param.description;
  945. }
  946. return msg;
  947. };
  948. SwaggerOperation.prototype.formatXml = function(xml) {
  949. var contexp, formatted, indent, lastType, lines, ln, pad, reg, transitions, wsexp, _fn, _i, _len;
  950. reg = /(>)(<)(\/*)/g;
  951. wsexp = /[ ]*(.*)[ ]+\n/g;
  952. contexp = /(<.+>)(.+\n)/g;
  953. xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
  954. pad = 0;
  955. formatted = '';
  956. lines = xml.split('\n');
  957. indent = 0;
  958. lastType = 'other';
  959. transitions = {
  960. 'single->single': 0,
  961. 'single->closing': -1,
  962. 'single->opening': 0,
  963. 'single->other': 0,
  964. 'closing->single': 0,
  965. 'closing->closing': -1,
  966. 'closing->opening': 0,
  967. 'closing->other': 0,
  968. 'opening->single': 1,
  969. 'opening->closing': 0,
  970. 'opening->opening': 1,
  971. 'opening->other': 1,
  972. 'other->single': 0,
  973. 'other->closing': -1,
  974. 'other->opening': 0,
  975. 'other->other': 0
  976. };
  977. _fn = function(ln) {
  978. var fromTo, j, key, padding, type, types, value;
  979. types = {
  980. single: Boolean(ln.match(/<.+\/>/)),
  981. closing: Boolean(ln.match(/<\/.+>/)),
  982. opening: Boolean(ln.match(/<[^!?].*>/))
  983. };
  984. type = ((function() {
  985. var _results;
  986. _results = [];
  987. for (key in types) {
  988. value = types[key];
  989. if (value) {
  990. _results.push(key);
  991. }
  992. }
  993. return _results;
  994. })())[0];
  995. type = type === void 0 ? 'other' : type;
  996. fromTo = lastType + '->' + type;
  997. lastType = type;
  998. padding = '';
  999. indent += transitions[fromTo];
  1000. padding = ((function() {
  1001. var _j, _ref5, _results;
  1002. _results = [];
  1003. for (j = _j = 0, _ref5 = indent; 0 <= _ref5 ? _j < _ref5 : _j > _ref5; j = 0 <= _ref5 ? ++_j : --_j) {
  1004. _results.push(' ');
  1005. }
  1006. return _results;
  1007. })()).join('');
  1008. if (fromTo === 'opening->closing') {
  1009. return formatted = formatted.substr(0, formatted.length - 1) + ln + '\n';
  1010. } else {
  1011. return formatted += padding + ln + '\n';
  1012. }
  1013. };
  1014. for (_i = 0, _len = lines.length; _i < _len; _i++) {
  1015. ln = lines[_i];
  1016. _fn(ln);
  1017. }
  1018. return formatted;
  1019. };
  1020. var SwaggerRequest = function(type, url, params, opts, successCallback, errorCallback, operation, execution) {
  1021. var _this = this;
  1022. var errors = [];
  1023. this.useJQuery = (typeof operation.resource.useJQuery !== 'undefined' ? operation.resource.useJQuery : null);
  1024. this.type = (type||errors.push("SwaggerRequest type is required (get/post/put/delete/patch/options)."));
  1025. this.url = (url||errors.push("SwaggerRequest url is required."));
  1026. this.params = params;
  1027. this.opts = opts;
  1028. this.successCallback = (successCallback||errors.push("SwaggerRequest successCallback is required."));
  1029. this.errorCallback = (errorCallback||errors.push("SwaggerRequest error callback is required."));
  1030. this.operation = (operation||errors.push("SwaggerRequest operation is required."));
  1031. this.execution = execution;
  1032. this.headers = (params.headers||{});
  1033. if(errors.length > 0) {
  1034. throw errors;
  1035. }
  1036. this.type = this.type.toUpperCase();
  1037. // set request, response content type headers
  1038. var headers = this.setHeaders(params, this.operation);
  1039. var body = params.body;
  1040. // encode the body for form submits
  1041. if (headers["Content-Type"]) {
  1042. var values = {};
  1043. var i;
  1044. var operationParams = this.operation.parameters;
  1045. for(i = 0; i < operationParams.length; i++) {
  1046. var param = operationParams[i];
  1047. if(param.paramType === "form")
  1048. values[param.name] = param;
  1049. }
  1050. if(headers["Content-Type"].indexOf("application/x-www-form-urlencoded") === 0) {
  1051. var encoded = "";
  1052. var key;
  1053. for(key in values) {
  1054. value = this.params[key];
  1055. if(typeof value !== 'undefined'){
  1056. if(encoded !== "")
  1057. encoded += "&";
  1058. encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
  1059. }
  1060. }
  1061. body = encoded;
  1062. }
  1063. else if (headers["Content-Type"].indexOf("multipart/form-data") === 0) {
  1064. // encode the body for form submits
  1065. var data = "";
  1066. var boundary = "----SwaggerFormBoundary" + Date.now();
  1067. var key;
  1068. for(key in values) {
  1069. value = this.params[key];
  1070. if(typeof value !== 'undefined') {
  1071. data += '--' + boundary + '\n';
  1072. data += 'Content-Disposition: form-data; name="' + key + '"';
  1073. data += '\n\n';
  1074. data += value + "\n";
  1075. }
  1076. }
  1077. data += "--" + boundary + "--\n";
  1078. headers["Content-Type"] = "multipart/form-data; boundary=" + boundary;
  1079. body = data;
  1080. }
  1081. }
  1082. if (!((this.headers != null) && (this.headers.mock != null))) {
  1083. obj = {
  1084. url: this.url,
  1085. method: this.type,
  1086. headers: headers,
  1087. body: body,
  1088. useJQuery: this.useJQuery,
  1089. on: {
  1090. error: function(response) {
  1091. return _this.errorCallback(response, _this.opts.parent);
  1092. },
  1093. redirect: function(response) {
  1094. return _this.successCallback(response, _this.opts.parent);
  1095. },
  1096. 307: function(response) {
  1097. return _this.successCallback(response, _this.opts.parent);
  1098. },
  1099. response: function(response) {
  1100. return _this.successCallback(response, _this.opts.parent);
  1101. }
  1102. }
  1103. };
  1104. var e;
  1105. if (typeof window !== 'undefined') {
  1106. e = window;
  1107. } else {
  1108. e = exports;
  1109. }
  1110. status = e.authorizations.apply(obj, this.operation.authorizations);
  1111. if (opts.mock == null) {
  1112. if (status !== false) {
  1113. new SwaggerHttp().execute(obj);
  1114. } else {
  1115. obj.canceled = true;
  1116. }
  1117. } else {
  1118. return obj;
  1119. }
  1120. }
  1121. };
  1122. SwaggerRequest.prototype.setHeaders = function(params, operation) {
  1123. // default type
  1124. var accepts = "application/json";
  1125. var consumes = "application/json";
  1126. var allDefinedParams = this.operation.parameters;
  1127. var definedFormParams = [];
  1128. var definedFileParams = [];
  1129. var body = params.body;
  1130. var headers = {};
  1131. // get params from the operation and set them in definedFileParams, definedFormParams, headers
  1132. var i;
  1133. for(i = 0; i < allDefinedParams.length; i++) {
  1134. var param = allDefinedParams[i];
  1135. if(param.paramType === "form")
  1136. definedFormParams.push(param);
  1137. else if(param.paramType === "file")
  1138. definedFileParams.push(param);
  1139. else if(param.paramType === "header" && this.params.headers) {
  1140. var key = param.name;
  1141. var headerValue = this.params.headers[param.name];
  1142. if(typeof this.params.headers[param.name] !== 'undefined')
  1143. headers[key] = headerValue;
  1144. }
  1145. }
  1146. // if there's a body, need to set the accepts header via requestContentType
  1147. if (body && (this.type === "POST" || this.type === "PUT" || this.type === "PATCH" || this.type === "DELETE")) {
  1148. if (this.opts.requestContentType)
  1149. consumes = this.opts.requestContentType;
  1150. } else {
  1151. // if any form params, content type must be set
  1152. if(definedFormParams.length > 0) {
  1153. if(definedFileParams.length > 0)
  1154. consumes = "multipart/form-data";
  1155. else
  1156. consumes = "application/x-www-form-urlencoded";
  1157. }
  1158. else if (this.type === "DELETE")
  1159. body = "{}";
  1160. else if (this.type != "DELETE")
  1161. accepts = null;
  1162. }
  1163. if (consumes && this.operation.consumes) {
  1164. if (this.operation.consumes.indexOf(consumes) === -1) {
  1165. log("server doesn't consume " + consumes + ", try " + JSON.stringify(this.operation.consumes));
  1166. consumes = this.operation.consumes[0];
  1167. }
  1168. }
  1169. if (this.opts.responseContentType) {
  1170. accepts = this.opts.responseContentType;
  1171. } else {
  1172. accepts = "application/json";
  1173. }
  1174. if (accepts && this.operation.produces) {
  1175. if (this.operation.produces.indexOf(accepts) === -1) {
  1176. log("server can't produce " + accepts);
  1177. accepts = this.operation.produces[0];
  1178. }
  1179. }
  1180. if ((consumes && body !== "") || (consumes === "application/x-www-form-urlencoded"))
  1181. headers["Content-Type"] = consumes;
  1182. if (accepts)
  1183. headers["Accept"] = accepts;
  1184. return headers;
  1185. }
  1186. SwaggerRequest.prototype.asCurl = function() {
  1187. var results = [];
  1188. if(this.headers) {
  1189. var key;
  1190. for(key in this.headers) {
  1191. results.push("--header \"" + key + ": " + this.headers[v] + "\"");
  1192. }
  1193. }
  1194. return "curl " + (results.join(" ")) + " " + this.url;
  1195. };
  1196. /**
  1197. * SwaggerHttp is a wrapper for executing requests
  1198. */
  1199. var SwaggerHttp = function() {};
  1200. SwaggerHttp.prototype.execute = function(obj) {
  1201. if(obj && (typeof obj.useJQuery === 'boolean'))
  1202. this.useJQuery = obj.useJQuery;
  1203. else
  1204. this.useJQuery = this.isIE8();
  1205. if(this.useJQuery)
  1206. return new JQueryHttpClient().execute(obj);
  1207. else
  1208. return new ShredHttpClient().execute(obj);
  1209. }
  1210. SwaggerHttp.prototype.isIE8 = function() {
  1211. var detectedIE = false;
  1212. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1213. nav = navigator.userAgent.toLowerCase();
  1214. if (nav.indexOf('msie') !== -1) {
  1215. var version = parseInt(nav.split('msie')[1]);
  1216. if (version <= 8) {
  1217. detectedIE = true;
  1218. }
  1219. }
  1220. }
  1221. return detectedIE;
  1222. };
  1223. /*
  1224. * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic.
  1225. * NOTE: when jQuery is available it will export both '$' and 'jQuery' to the global space.
  1226. * Since we are using closures here we need to alias it for internal use.
  1227. */
  1228. var JQueryHttpClient = function(options) {
  1229. "use strict";
  1230. if(!jQuery){
  1231. var jQuery = window.jQuery;
  1232. }
  1233. }
  1234. JQueryHttpClient.prototype.execute = function(obj) {
  1235. var cb = obj.on;
  1236. var request = obj;
  1237. obj.type = obj.method;
  1238. obj.cache = false;
  1239. obj.beforeSend = function(xhr) {
  1240. var key, results;
  1241. if (obj.headers) {
  1242. results = [];
  1243. var key;
  1244. for (key in obj.headers) {
  1245. if (key.toLowerCase() === "content-type") {
  1246. results.push(obj.contentType = obj.headers[key]);
  1247. } else if (key.toLowerCase() === "accept") {
  1248. results.push(obj.accepts = obj.headers[key]);
  1249. } else {
  1250. results.push(xhr.setRequestHeader(key, obj.headers[key]));
  1251. }
  1252. }
  1253. return results;
  1254. }
  1255. };
  1256. obj.data = obj.body;
  1257. obj.complete = function(response, textStatus, opts) {
  1258. var headers = {},
  1259. headerArray = response.getAllResponseHeaders().split("\n");
  1260. for(var i = 0; i < headerArray.length; i++) {
  1261. var toSplit = headerArray[i].trim();
  1262. if(toSplit.length === 0)
  1263. continue;
  1264. var separator = toSplit.indexOf(":");
  1265. if(separator === -1) {
  1266. // Name but no value in the header
  1267. headers[toSplit] = null;
  1268. continue;
  1269. }
  1270. var name = toSplit.substring(0, separator).trim(),
  1271. value = toSplit.substring(separator + 1).trim();
  1272. headers[name] = value;
  1273. }
  1274. var out = {
  1275. url: request.url,
  1276. method: request.method,
  1277. status: response.status,
  1278. data: response.responseText,
  1279. headers: headers
  1280. };
  1281. var contentType = (headers["content-type"]||headers["Content-Type"]||null)
  1282. if(contentType != null) {
  1283. if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
  1284. if(response.responseText && response.responseText !== "")
  1285. out.obj = JSON.parse(response.responseText);
  1286. else
  1287. out.obj = {}
  1288. }
  1289. }
  1290. if(response.status >= 200 && response.status < 300)
  1291. cb.response(out);
  1292. else if(response.status === 0 || (response.status >= 400 && response.status < 599))
  1293. cb.error(out);
  1294. else
  1295. return cb.response(out);
  1296. };
  1297. jQuery.support.cors = true;
  1298. return jQuery.ajax(obj);
  1299. }
  1300. /*
  1301. * ShredHttpClient is a light-weight, node or browser HTTP client
  1302. */
  1303. var ShredHttpClient = function(options) {
  1304. this.options = (options||{});
  1305. this.isInitialized = false;
  1306. var identity, toString;
  1307. if (typeof window !== 'undefined') {
  1308. this.Shred = require("./shred");
  1309. this.content = require("./shred/content");
  1310. }
  1311. else
  1312. this.Shred = require("shred");
  1313. this.shred = new this.Shred();
  1314. }
  1315. ShredHttpClient.prototype.initShred = function () {
  1316. this.isInitialized = true;
  1317. this.registerProcessors(this.shred);
  1318. }
  1319. ShredHttpClient.prototype.registerProcessors = function(shred) {
  1320. var identity = function(x) {
  1321. return x;
  1322. };
  1323. var toString = function(x) {
  1324. return x.toString();
  1325. };
  1326. if (typeof window !== 'undefined') {
  1327. this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
  1328. parser: identity,
  1329. stringify: toString
  1330. });
  1331. } else {
  1332. this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
  1333. parser: identity,
  1334. stringify: toString
  1335. });
  1336. }
  1337. }
  1338. ShredHttpClient.prototype.execute = function(obj) {
  1339. if(!this.isInitialized)
  1340. this.initShred();
  1341. var cb = obj.on, res;
  1342. var transform = function(response) {
  1343. var out = {
  1344. headers: response._headers,
  1345. url: response.request.url,
  1346. method: response.request.method,
  1347. status: response.status,
  1348. data: response.content.data
  1349. };
  1350. var contentType = (response._headers["content-type"]||response._headers["Content-Type"]||null)
  1351. if(contentType != null) {
  1352. if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
  1353. if(response.content.data && response.content.data !== "")
  1354. out.obj = JSON.parse(response.content.data);
  1355. else
  1356. out.obj = {}
  1357. }
  1358. }
  1359. return out;
  1360. };
  1361. // Transform an error into a usable response-like object
  1362. var transformError = function(error) {
  1363. var out = {
  1364. // Default to a status of 0 - The client will treat this as a generic permissions sort of error
  1365. status: 0,
  1366. data: error.message || error
  1367. };
  1368. if(error.code) {
  1369. out.obj = error;
  1370. if(error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED' ) {
  1371. // We can tell the client that this should be treated as a missing resource and not as a permissions thing
  1372. out.status = 404;
  1373. }
  1374. }
  1375. return out;
  1376. };
  1377. res = {
  1378. error: function(response) {
  1379. if (obj)
  1380. return cb.error(transform(response));
  1381. },
  1382. // Catch the Shred error raised when the request errors as it is made (i.e. No Response is coming)
  1383. request_error: function(err) {
  1384. if(obj)
  1385. return cb.error(transformError(err));
  1386. },
  1387. redirect: function(response) {
  1388. if (obj)
  1389. return cb.redirect(transform(response));
  1390. },
  1391. 307: function(response) {
  1392. if (obj)
  1393. return cb.redirect(transform(response));
  1394. },
  1395. response: function(response) {
  1396. if (obj)
  1397. return cb.response(transform(response));
  1398. }
  1399. };
  1400. if (obj) {
  1401. obj.on = res;
  1402. }
  1403. return this.shred.request(obj);
  1404. };
  1405. /**
  1406. * SwaggerAuthorizations applys the correct authorization to an operation being executed
  1407. */
  1408. var SwaggerAuthorizations = function() {
  1409. this.authz = {};
  1410. };
  1411. SwaggerAuthorizations.prototype.add = function(name, auth) {
  1412. this.authz[name] = auth;
  1413. return auth;
  1414. };
  1415. SwaggerAuthorizations.prototype.remove = function(name) {
  1416. return delete this.authz[name];
  1417. };
  1418. SwaggerAuthorizations.prototype.apply = function(obj, authorizations) {
  1419. var status = null;
  1420. var key;
  1421. // if the "authorizations" key is undefined, or has an empty array, add all keys
  1422. if(typeof authorizations === 'undefined' || Object.keys(authorizations).length == 0) {
  1423. for (key in this.authz) {
  1424. value = this.authz[key];
  1425. result = value.apply(obj, authorizations);
  1426. if (result === true)
  1427. status = true;
  1428. }
  1429. }
  1430. else {
  1431. for(name in authorizations) {
  1432. for (key in this.authz) {
  1433. if(key == name) {
  1434. value = this.authz[key];
  1435. result = value.apply(obj, authorizations);
  1436. if (result === true)
  1437. status = true;
  1438. }
  1439. }
  1440. }
  1441. }
  1442. return status;
  1443. };
  1444. /**
  1445. * ApiKeyAuthorization allows a query param or header to be injected
  1446. */
  1447. var ApiKeyAuthorization = function(name, value, type, delimiter) {
  1448. this.name = name;
  1449. this.value = value;
  1450. this.type = type;
  1451. this.delimiter = delimiter;
  1452. };
  1453. ApiKeyAuthorization.prototype.apply = function(obj, authorizations) {
  1454. if (this.type === "query") {
  1455. if (obj.url.indexOf('?') > 0)
  1456. obj.url = obj.url + "&" + this.name + "=" + this.value;
  1457. else
  1458. obj.url = obj.url + "?" + this.name + "=" + this.value;
  1459. return true;
  1460. } else if (this.type === "header") {
  1461. if(typeof obj.headers[this.name] !== 'undefined') {
  1462. if(typeof this.delimiter !== 'undefined')
  1463. obj.headers[this.name] = obj.headers[this.name] + this.delimiter + this.value;
  1464. }
  1465. else
  1466. obj.headers[this.name] = this.value;
  1467. return true;
  1468. }
  1469. };
  1470. var CookieAuthorization = function(cookie) {
  1471. this.cookie = cookie;
  1472. }
  1473. CookieAuthorization.prototype.apply = function(obj, authorizations) {
  1474. obj.cookieJar = obj.cookieJar || CookieJar();
  1475. obj.cookieJar.setCookie(this.cookie);
  1476. return true;
  1477. }
  1478. /**
  1479. * Password Authorization is a basic auth implementation
  1480. */
  1481. var PasswordAuthorization = function(name, username, password) {
  1482. this.name = name;
  1483. this.username = username;
  1484. this.password = password;
  1485. this._btoa = null;
  1486. if (typeof window !== 'undefined')
  1487. this._btoa = btoa;
  1488. else
  1489. this._btoa = require("btoa");
  1490. };
  1491. PasswordAuthorization.prototype.apply = function(obj, authorizations) {
  1492. var base64encoder = this._btoa;
  1493. obj.headers["Authorization"] = "Basic " + base64encoder(this.username + ":" + this.password);
  1494. return true;
  1495. };
  1496. var e = (typeof window !== 'undefined' ? window : exports);
  1497. var sampleModels = {};
  1498. var cookies = {};
  1499. e.SampleModels = sampleModels;
  1500. e.SwaggerHttp = SwaggerHttp;
  1501. e.SwaggerRequest = SwaggerRequest;
  1502. e.authorizations = new SwaggerAuthorizations();
  1503. e.ApiKeyAuthorization = ApiKeyAuthorization;
  1504. e.PasswordAuthorization = PasswordAuthorization;
  1505. e.CookieAuthorization = CookieAuthorization;
  1506. e.JQueryHttpClient = JQueryHttpClient;
  1507. e.ShredHttpClient = ShredHttpClient;
  1508. e.SwaggerOperation = SwaggerOperation;
  1509. e.SwaggerModel = SwaggerModel;
  1510. e.SwaggerModelProperty = SwaggerModelProperty;
  1511. e.SwaggerResource = SwaggerResource;
  1512. e.SwaggerApi = SwaggerApi;