選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

1726 行
54 KiB

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