Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 

1615 Zeilen
44 KiB

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