Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

1500 righe
40 KiB

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