2 * Copyright 2016 ZTE Corporation.
\r
4 * Licensed under the Apache License, Version 2.0 (the "License");
\r
5 * you may not use this file except in compliance with the License.
\r
6 * You may obtain a copy of the License at
\r
8 * http://www.apache.org/licenses/LICENSE-2.0
\r
10 * Unless required by applicable law or agreed to in writing, software
\r
11 * distributed under the License is distributed on an "AS IS" BASIS,
\r
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
13 * See the License for the specific language governing permissions and
\r
14 * limitations under the License.
\r
17 * swagger-client - swagger.js is a javascript client for use with swaggering APIs.
\r
18 * @version v2.1.9-M1
\r
19 * @link http://swagger.io
\r
20 * @license apache 2.0
\r
23 var ArrayModel = function(definition) {
\r
24 this.name = "arrayModel";
\r
25 this.definition = definition || {};
\r
26 this.properties = [];
\r
28 var requiredFields = definition.enum || [];
\r
29 var innerType = definition.items;
\r
31 if(innerType.type) {
\r
32 this.type = typeFromJsonSchema(innerType.type, innerType.format);
\r
35 this.ref = innerType.$ref;
\r
41 ArrayModel.prototype.createJSONSample = function(modelsToIgnore) {
\r
43 modelsToIgnore = (modelsToIgnore||{});
\r
47 else if (this.ref) {
\r
48 var name = simpleRef(this.ref);
\r
49 if(typeof modelsToIgnore[name] === 'undefined') {
\r
50 modelsToIgnore[name] = this;
\r
51 result = models[name].createJSONSample(modelsToIgnore);
\r
60 ArrayModel.prototype.getSampleValue = function(modelsToIgnore) {
\r
62 modelsToIgnore = (modelsToIgnore || {});
\r
66 else if (this.ref) {
\r
67 var name = simpleRef(this.ref);
\r
68 result = models[name].getSampleValue(modelsToIgnore);
\r
73 ArrayModel.prototype.getMockSignature = function(modelsToIgnore) {
\r
74 var propertiesStr = [];
\r
76 for (i = 0; i < this.properties.length; i++) {
\r
77 prop = this.properties[i];
\r
78 propertiesStr.push(prop.toString());
\r
81 var strong = '<span class="strong">';
\r
82 var stronger = '<span class="stronger">';
\r
83 var strongClose = '</span>';
\r
84 var classOpen = strong + 'array' + ' {' + strongClose;
\r
85 var classClose = strong + '}' + strongClose;
\r
86 var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
\r
88 if (!modelsToIgnore)
\r
89 modelsToIgnore = {};
\r
90 modelsToIgnore[this.name] = this;
\r
91 for (i = 0; i < this.properties.length; i++) {
\r
92 prop = this.properties[i];
\r
93 var ref = prop.$ref;
\r
94 var model = models[ref];
\r
95 if (model && typeof modelsToIgnore[ref] === 'undefined') {
\r
96 returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
\r
104 * SwaggerAuthorizations applys the correct authorization to an operation being executed
\r
106 var SwaggerAuthorizations = function() {
\r
110 SwaggerAuthorizations.prototype.add = function(name, auth) {
\r
111 this.authz[name] = auth;
\r
115 SwaggerAuthorizations.prototype.remove = function(name) {
\r
116 return delete this.authz[name];
\r
119 SwaggerAuthorizations.prototype.apply = function (obj, authorizations) {
\r
121 var key, name, value, result;
\r
123 // if the "authorizations" key is undefined, or has an empty array, add all keys
\r
124 if (typeof authorizations === 'undefined' || Object.keys(authorizations).length === 0) {
\r
125 for (key in this.authz) {
\r
126 value = this.authz[key];
\r
127 result = value.apply(obj, authorizations);
\r
128 if (result === true)
\r
134 if (Array.isArray(authorizations)) {
\r
136 for (var i = 0; i < authorizations.length; i++) {
\r
137 var auth = authorizations[i];
\r
138 for (name in auth) {
\r
139 for (key in this.authz) {
\r
141 value = this.authz[key];
\r
142 result = value.apply(obj, authorizations);
\r
143 if (result === true)
\r
152 for (name in authorizations) {
\r
153 for (key in this.authz) {
\r
155 value = this.authz[key];
\r
156 result = value.apply(obj, authorizations);
\r
157 if (result === true)
\r
169 * ApiKeyAuthorization allows a query param or header to be injected
\r
171 var ApiKeyAuthorization = function(name, value, type) {
\r
173 this.value = value;
\r
177 ApiKeyAuthorization.prototype.apply = function(obj, authorizations) {
\r
178 if (this.type === "query") {
\r
179 if (obj.url.indexOf('?') > 0)
\r
180 obj.url = obj.url + "&" + this.name + "=" + this.value;
\r
182 obj.url = obj.url + "?" + this.name + "=" + this.value;
\r
184 } else if (this.type === "header") {
\r
185 obj.headers[this.name] = this.value;
\r
190 var CookieAuthorization = function(cookie) {
\r
191 this.cookie = cookie;
\r
194 CookieAuthorization.prototype.apply = function(obj, authorizations) {
\r
195 obj.cookieJar = obj.cookieJar || CookieJar();
\r
196 obj.cookieJar.setCookie(this.cookie);
\r
201 * Password Authorization is a basic auth implementation
\r
203 var PasswordAuthorization = function(name, username, password) {
\r
205 this.username = username;
\r
206 this.password = password;
\r
208 if (typeof window !== 'undefined')
\r
211 this._btoa = require("btoa");
\r
214 PasswordAuthorization.prototype.apply = function(obj, authorizations) {
\r
215 var base64encoder = this._btoa;
\r
216 obj.headers.Authorization = "Basic " + base64encoder(this.username + ":" + this.password);
\r
219 var __bind = function(fn, me){
\r
221 return fn.apply(me, arguments);
\r
225 fail = function(message) {
\r
230 log.history = log.history || [];
\r
231 log.history.push(arguments);
\r
233 console.log( Array.prototype.slice.call(arguments)[0] );
\r
237 if (!Array.prototype.indexOf) {
\r
238 Array.prototype.indexOf = function(obj, start) {
\r
239 for (var i = (start || 0), j = this.length; i < j; i++) {
\r
240 if (this[i] === obj) { return i; }
\r
247 * allows override of the default value based on the parameter being
\r
250 var applyParameterMacro = function (operation, parameter) {
\r
251 var e = (typeof window !== 'undefined' ? window : exports);
\r
252 if(e.parameterMacro)
\r
253 return e.parameterMacro(operation, parameter);
\r
255 return parameter.defaultValue;
\r
259 * allows overriding the default value of an model property
\r
261 var applyModelPropertyMacro = function (model, property) {
\r
262 var e = (typeof window !== 'undefined' ? window : exports);
\r
263 if(e.modelPropertyMacro)
\r
264 return e.modelPropertyMacro(model, property);
\r
266 return property.defaultValue;
\r
272 var PrimitiveModel = function(definition) {
\r
273 this.name = "name";
\r
274 this.definition = definition || {};
\r
275 this.properties = [];
\r
277 var requiredFields = definition.enum || [];
\r
278 this.type = typeFromJsonSchema(definition.type, definition.format);
\r
281 PrimitiveModel.prototype.createJSONSample = function(modelsToIgnore) {
\r
282 var result = this.type;
\r
286 PrimitiveModel.prototype.getSampleValue = function() {
\r
287 var result = this.type;
\r
291 PrimitiveModel.prototype.getMockSignature = function(modelsToIgnore) {
\r
292 var propertiesStr = [];
\r
294 for (i = 0; i < this.properties.length; i++) {
\r
295 prop = this.properties[i];
\r
296 propertiesStr.push(prop.toString());
\r
299 var strong = '<span class="strong">';
\r
300 var stronger = '<span class="stronger">';
\r
301 var strongClose = '</span>';
\r
302 var classOpen = strong + this.name + ' {' + strongClose;
\r
303 var classClose = strong + '}' + strongClose;
\r
304 var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
\r
306 if (!modelsToIgnore)
\r
307 modelsToIgnore = {};
\r
308 modelsToIgnore[this.name] = this;
\r
309 for (i = 0; i < this.properties.length; i++) {
\r
310 prop = this.properties[i];
\r
311 var ref = prop.$ref;
\r
312 var model = models[ref];
\r
313 if (model && typeof modelsToIgnore[ref] === 'undefined') {
\r
314 returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
\r
320 * Resolves a spec's remote references
\r
322 var Resolver = function (){};
\r
324 Resolver.prototype.resolve = function(spec, callback, scope) {
\r
325 this.scope = (scope || this);
\r
326 var host, name, path, property, propertyName, type;
\r
327 var processedCalls = 0, resolvedRefs = {}, unresolvedRefs = {};
\r
329 // store objects for dereferencing
\r
330 var resolutionTable = {};
\r
333 for(name in spec.definitions) {
\r
334 var model = spec.definitions[name];
\r
335 for(propertyName in model.properties) {
\r
336 property = model.properties[propertyName];
\r
337 this.resolveTo(property, resolutionTable);
\r
341 for(name in spec.paths) {
\r
342 var method, operation, responseCode;
\r
343 path = spec.paths[name];
\r
344 for(method in path) {
\r
345 operation = path[method];
\r
346 var i, parameters = operation.parameters;
\r
347 for(i in parameters) {
\r
348 var parameter = parameters[i];
\r
349 if(parameter.in === 'body' && parameter.schema) {
\r
350 this.resolveTo(parameter.schema, resolutionTable);
\r
352 if(parameter.$ref) {
\r
353 this.resolveInline(spec, parameter, resolutionTable, unresolvedRefs);
\r
356 for(responseCode in operation.responses) {
\r
357 var response = operation.responses[responseCode];
\r
358 if(response.schema) {
\r
359 this.resolveTo(response.schema, resolutionTable);
\r
365 var opts = {}, expectedCalls = 0;
\r
366 for(name in resolutionTable) {
\r
367 var parts = name.split('#');
\r
368 if(parts.length == 2) {
\r
369 host = parts[0]; path = parts[1];
\r
370 if(!Array.isArray(opts[host])) {
\r
372 expectedCalls += 1;
\r
374 opts[host].push(path);
\r
378 for(name in opts) {
\r
379 var self = this, opt = opts[name];
\r
383 useJQuery: false, // TODO
\r
387 accept: this.scope.swaggerRequestHeaders || 'application/json'
\r
390 error: function(response) {
\r
391 processedCalls += 1;
\r
393 for(i = 0; i < opt.length; i++) {
\r
394 // fail all of these
\r
395 var resolved = host + '#' + opt[i];
\r
396 unresolvedRefs[resolved] = null;
\r
398 if(processedCalls === expectedCalls)
\r
399 self.finish(spec, resolutionTable, resolvedRefs, unresolvedRefs, callback);
\r
401 response: function(response) {
\r
402 var i, j, swagger = response.obj;
\r
403 processedCalls += 1;
\r
404 for(i = 0; i < opt.length; i++) {
\r
405 var location = swagger, path = opt[i], parts = path.split('/');
\r
406 for(j = 0; j < parts.length; j++) {
\r
407 var segment = parts[j];
\r
408 if(typeof location === 'undefined')
\r
410 if(segment.length > 0)
\r
411 location = location[segment];
\r
413 var resolved = host + '#' + path, resolvedName = parts[j-1];
\r
414 if(typeof location !== 'undefined') {
\r
415 resolvedRefs[resolved] = {
\r
416 name: resolvedName,
\r
420 else unresolvedRefs[resolved] = null;
\r
422 if(processedCalls === expectedCalls)
\r
423 self.finish(spec, resolutionTable, resolvedRefs, unresolvedRefs, callback);
\r
427 authorizations.apply(obj);
\r
428 new SwaggerHttp().execute(obj);
\r
430 if(Object.keys(opts).length === 0)
\r
431 callback.call(this.scope, spec, unresolvedRefs);
\r
434 Resolver.prototype.finish = function(spec, resolutionTable, resolvedRefs, unresolvedRefs, callback) {
\r
435 // walk resolution table and replace with resolved refs
\r
437 for(ref in resolutionTable) {
\r
438 var i, locations = resolutionTable[ref];
\r
439 for(i = 0; i < locations.length; i++) {
\r
440 var resolvedTo = resolvedRefs[locations[i].obj.$ref];
\r
442 if(!spec.definitions)
\r
443 spec.definitions = {};
\r
444 if(locations[i].resolveAs === '$ref') {
\r
445 spec.definitions[resolvedTo.name] = resolvedTo.obj;
\r
446 locations[i].obj.$ref = '#/definitions/' + resolvedTo.name;
\r
448 else if (locations[i].resolveAs === 'inline') {
\r
450 var targetObj = locations[i].obj;
\r
451 delete targetObj.$ref;
\r
452 for(key in resolvedTo.obj) {
\r
453 targetObj[key] = resolvedTo.obj[key];
\r
459 callback.call(this.scope, spec, unresolvedRefs);
\r
463 * immediately in-lines local refs, queues remote refs
\r
464 * for inline resolution
\r
466 Resolver.prototype.resolveInline = function (spec, property, objs, unresolvedRefs) {
\r
467 var ref = property.$ref;
\r
469 if(ref.indexOf('http') === 0) {
\r
470 if(Array.isArray(objs[ref])) {
\r
471 objs[ref].push({obj: property, resolveAs: 'inline'});
\r
474 objs[ref] = [{obj: property, resolveAs: 'inline'}];
\r
477 else if (ref.indexOf('#') === 0) {
\r
479 var shortenedRef = ref.substring(1);
\r
480 var i, parts = shortenedRef.split('/'), location = spec;
\r
481 for(i = 0; i < parts.length; i++) {
\r
482 var part = parts[i];
\r
483 if(part.length > 0) {
\r
484 location = location[part];
\r
488 delete property.$ref;
\r
490 for(key in location) {
\r
491 property[key] = location[key];
\r
494 else unresolvedRefs[ref] = null;
\r
497 else if(property.type === 'array') {
\r
498 this.resolveTo(property.items, objs);
\r
502 Resolver.prototype.resolveTo = function (property, objs) {
\r
503 var ref = property.$ref;
\r
505 if(ref.indexOf('http') === 0) {
\r
506 if(Array.isArray(objs[ref])) {
\r
507 objs[ref].push({obj: property, resolveAs: '$ref'});
\r
510 objs[ref] = [{obj: property, resolveAs: '$ref'}];
\r
514 else if(property.type === 'array') {
\r
515 var items = property.items;
\r
516 this.resolveTo(items, objs);
\r
519 var addModel = function(name, model) {
\r
520 models[name] = model;
\r
523 var SwaggerClient = function(url, options) {
\r
524 this.isBuilt = false;
\r
526 this.debug = false;
\r
527 this.basePath = null;
\r
528 this.modelsArray = [];
\r
529 this.authorizations = null;
\r
530 this.authorizationScheme = null;
\r
531 this.isValid = false;
\r
533 this.useJQuery = false;
\r
534 this.resourceCount = 0;
\r
536 if(typeof url !== 'undefined')
\r
537 return this.initialize(url, options);
\r
540 SwaggerClient.prototype.initialize = function (url, options) {
\r
541 this.models = models = {};
\r
543 options = (options||{});
\r
545 if(typeof url === 'string')
\r
547 else if(typeof url === 'object') {
\r
549 this.url = options.url;
\r
551 this.swaggerRequstHeaders = options.swaggerRequstHeaders || 'application/json;charset=utf-8,*/*';
\r
552 this.defaultSuccessCallback = options.defaultSuccessCallback || null;
\r
553 this.defaultErrorCallback = options.defaultErrorCallback || null;
\r
555 if (typeof options.success === 'function')
\r
556 this.success = options.success;
\r
558 if (options.useJQuery)
\r
559 this.useJQuery = options.useJQuery;
\r
561 if (options.authorizations) {
\r
562 this.clientAuthorizations = options.authorizations;
\r
564 this.clientAuthorizations = authorizations;
\r
567 this.supportedSubmitMethods = options.supportedSubmitMethods || [];
\r
568 this.failure = options.failure || function() {};
\r
569 this.progress = options.progress || function() {};
\r
570 this.spec = options.spec;
\r
571 this.options = options;
\r
573 if (typeof options.success === 'function') {
\r
579 SwaggerClient.prototype.build = function(mock) {
\r
580 if (this.isBuilt) return this;
\r
582 this.progress('fetching resource list: ' + this.url);
\r
584 useJQuery: this.useJQuery,
\r
588 accept: this.swaggerRequstHeaders
\r
591 error: function(response) {
\r
592 if (self.url.substring(0, 4) !== 'http')
\r
593 return self.fail('Please specify the protocol for ' + self.url);
\r
594 else if (response.status === 0)
\r
595 return self.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.');
\r
596 else if (response.status === 404)
\r
597 return self.fail('Can\'t read swagger JSON from ' + self.url);
\r
599 return self.fail(response.status + ' : ' + response.statusText + ' ' + self.url);
\r
601 response: function(resp) {
\r
602 var responseObj = resp.obj || JSON.parse(resp.data);
\r
603 self.swaggerVersion = responseObj.swaggerVersion;
\r
605 if(responseObj.swagger && parseInt(responseObj.swagger) === 2) {
\r
606 self.swaggerVersion = responseObj.swagger;
\r
607 new Resolver().resolve(responseObj, self.buildFromSpec, self);
\r
608 self.isValid = true;
\r
611 if (self.swaggerVersion === '1.2') {
\r
612 return self.buildFrom1_2Spec(responseObj);
\r
614 return self.buildFrom1_1Spec(responseObj);
\r
621 setTimeout(function() {
\r
622 new Resolver().resolve(self.spec, self.buildFromSpec, self);
\r
626 authorizations.apply(obj);
\r
629 new SwaggerHttp().execute(obj);
\r
634 SwaggerClient.prototype.buildFromSpec = function(response) {
\r
635 if(this.isBuilt) return this;
\r
637 this.info = response.info || {};
\r
638 this.title = response.title || '';
\r
639 this.host = response.host || '';
\r
640 this.schemes = response.schemes || [];
\r
641 this.basePath = response.basePath || '';
\r
643 this.apisArray = [];
\r
644 this.consumes = response.consumes;
\r
645 this.produces = response.produces;
\r
646 this.securityDefinitions = response.securityDefinitions;
\r
649 this.authSchemes = response.securityDefinitions;
\r
651 var definedTags = {};
\r
652 if(Array.isArray(response.tags)) {
\r
654 for(k = 0; k < response.tags.length; k++) {
\r
655 var t = response.tags[k];
\r
656 definedTags[t.name] = t;
\r
661 if(typeof this.url === 'string') {
\r
662 location = this.parseUri(this.url);
\r
665 if(typeof this.schemes === 'undefined' || this.schemes.length === 0) {
\r
666 this.scheme = location.scheme || 'http';
\r
669 this.scheme = this.schemes[0];
\r
672 if(typeof this.host === 'undefined' || this.host === '') {
\r
673 this.host = location.host;
\r
674 if (location.port) {
\r
675 this.host = this.host + ':' + location.port;
\r
679 this.definitions = response.definitions;
\r
681 for(key in this.definitions) {
\r
682 var model = new Model(key, this.definitions[key]);
\r
684 models[key] = model;
\r
688 // get paths, create functions for each operationId
\r
690 var operations = [];
\r
691 for(path in response.paths) {
\r
692 if(typeof response.paths[path] === 'object') {
\r
694 for(httpMethod in response.paths[path]) {
\r
695 if(['delete', 'get', 'head', 'options', 'patch', 'post', 'put'].indexOf(httpMethod) === -1) {
\r
698 var operation = response.paths[path][httpMethod];
\r
699 var tags = operation.tags;
\r
700 if(typeof tags === 'undefined') {
\r
701 operation.tags = [ 'default' ];
\r
702 tags = operation.tags;
\r
704 var operationId = this.idFromOp(path, httpMethod, operation);
\r
705 var operationObject = new Operation (
\r
714 // bind this operation's execute command to the api
\r
715 if(tags.length > 0) {
\r
717 for(i = 0; i < tags.length; i++) {
\r
718 var tag = this.tagFromLabel(tags[i]);
\r
719 var operationGroup = this[tag];
\r
720 if(typeof this.apis[tag] === 'undefined')
\r
721 this.apis[tag] = {};
\r
722 if(typeof operationGroup === 'undefined') {
\r
724 operationGroup = this[tag];
\r
725 operationGroup.operations = {};
\r
726 operationGroup.label = tag;
\r
727 operationGroup.apis = [];
\r
728 var tagObject = definedTags[tag];
\r
729 if(typeof tagObject === 'object') {
\r
730 operationGroup.description = tagObject.description;
\r
731 operationGroup.externalDocs = tagObject.externalDocs;
\r
733 this[tag].help = this.help.bind(operationGroup);
\r
734 this.apisArray.push(new OperationGroup(tag, operationGroup.description, operationGroup.externalDocs, operationObject));
\r
736 if(typeof this.apis[tag].help !== 'function')
\r
737 this.apis[tag].help = this.help.bind(operationGroup);
\r
738 // bind to the apis object
\r
739 this.apis[tag][operationId] = operationObject.execute.bind(operationObject);
\r
740 this.apis[tag][operationId].help = operationObject.help.bind(operationObject);
\r
741 this.apis[tag][operationId].asCurl = operationObject.asCurl.bind(operationObject);
\r
742 operationGroup[operationId] = operationObject.execute.bind(operationObject);
\r
743 operationGroup[operationId].help = operationObject.help.bind(operationObject);
\r
744 operationGroup[operationId].asCurl = operationObject.asCurl.bind(operationObject);
\r
746 operationGroup.apis.push(operationObject);
\r
747 operationGroup.operations[operationId] = operationObject;
\r
749 // legacy UI feature
\r
752 for(j = 0; j < this.apisArray.length; j++) {
\r
753 if(this.apisArray[j].tag === tag) {
\r
754 api = this.apisArray[j];
\r
758 api.operationsArray.push(operationObject);
\r
763 log('no group to bind to');
\r
768 this.isBuilt = true;
\r
769 if (this.success) {
\r
770 this.isValid = true;
\r
771 this.isBuilt = true;
\r
777 SwaggerClient.prototype.parseUri = function(uri) {
\r
778 var urlParseRE = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/;
\r
779 var parts = urlParseRE.exec(uri);
\r
781 scheme: parts[4].replace(':',''),
\r
788 SwaggerClient.prototype.help = function(dontPrint) {
\r
790 var output = 'operations for the "' + this.label + '" tag';
\r
791 for(i = 0; i < this.apis.length; i++) {
\r
792 var api = this.apis[i];
\r
793 output += '\n * ' + api.nickname + ': ' + api.operation.summary;
\r
803 SwaggerClient.prototype.tagFromLabel = function(label) {
\r
807 SwaggerClient.prototype.idFromOp = function(path, httpMethod, op) {
\r
808 var opId = op.operationId || (path.substring(1) + '_' + httpMethod);
\r
809 return opId.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()\+\s]/g,'_');
\r
812 SwaggerClient.prototype.fail = function(message) {
\r
813 this.failure(message);
\r
817 var OperationGroup = function(tag, description, externalDocs, operation) {
\r
820 this.description = description;
\r
821 this.externalDocs = externalDocs;
\r
823 this.operation = operation;
\r
824 this.operationsArray = [];
\r
827 var Operation = function(parent, scheme, operationId, httpMethod, path, args, definitions) {
\r
829 parent = parent||{};
\r
832 this.operations = {};
\r
833 this.operation = args;
\r
834 this.deprecated = args.deprecated;
\r
835 this.consumes = args.consumes;
\r
836 this.produces = args.produces;
\r
837 this.parent = parent;
\r
838 this.host = parent.host || 'localhost';
\r
839 this.schemes = parent.schemes;
\r
840 this.scheme = scheme || parent.scheme || 'http';
\r
841 this.basePath = parent.basePath || '/';
\r
842 this.nickname = (operationId||errors.push('Operations must have a nickname.'));
\r
843 this.method = (httpMethod||errors.push('Operation ' + operationId + ' is missing method.'));
\r
844 this.path = (path||errors.push('Operation ' + this.nickname + ' is missing path.'));
\r
845 this.parameters = args !== null ? (args.parameters||[]) : {};
\r
846 this.summary = args.summary || '';
\r
847 this.responses = (args.responses||{});
\r
849 this.security = args.security;
\r
850 this.authorizations = args.security;
\r
851 this.description = args.description;
\r
852 this.useJQuery = parent.useJQuery;
\r
854 if(typeof this.deprecated === 'string') {
\r
855 switch(this.deprecated.toLowerCase()) {
\r
856 case 'true': case 'yes': case '1': {
\r
857 this.deprecated = true;
\r
860 case 'false': case 'no': case '0': case null: {
\r
861 this.deprecated = false;
\r
864 default: this.deprecated = Boolean(this.deprecated);
\r
871 // add to global models
\r
873 for(key in this.definitions) {
\r
874 model = new Model(key, definitions[key]);
\r
876 models[key] = model;
\r
880 for(i = 0; i < this.parameters.length; i++) {
\r
881 var param = this.parameters[i];
\r
882 if(param.type === 'array') {
\r
883 param.isList = true;
\r
884 param.allowMultiple = true;
\r
886 var innerType = this.getType(param);
\r
887 if(innerType && innerType.toString().toLowerCase() === 'boolean') {
\r
888 param.allowableValues = {};
\r
889 param.isList = true;
\r
890 param['enum'] = ["true", "false"];
\r
892 if(typeof param['enum'] !== 'undefined') {
\r
894 param.allowableValues = {};
\r
895 param.allowableValues.values = [];
\r
896 param.allowableValues.descriptiveValues = [];
\r
897 for(id = 0; id < param['enum'].length; id++) {
\r
898 var value = param['enum'][id];
\r
899 var isDefault = (value === param.default) ? true : false;
\r
900 param.allowableValues.values.push(value);
\r
901 param.allowableValues.descriptiveValues.push({value : value, isDefault: isDefault});
\r
904 if(param.type === 'array') {
\r
905 innerType = [innerType];
\r
906 if(typeof param.allowableValues === 'undefined') {
\r
907 // can't show as a list if no values to select from
\r
908 delete param.isList;
\r
909 delete param.allowMultiple;
\r
912 param.signature = this.getModelSignature(innerType, models).toString();
\r
913 param.sampleJSON = this.getModelSampleJSON(innerType, models);
\r
914 param.responseClassSignature = param.signature;
\r
917 var defaultResponseCode, response, responses = this.responses;
\r
919 if(responses['200']) {
\r
920 response = responses['200'];
\r
921 defaultResponseCode = '200';
\r
923 else if(responses['201']) {
\r
924 response = responses['201'];
\r
925 defaultResponseCode = '201';
\r
927 else if(responses['202']) {
\r
928 response = responses['202'];
\r
929 defaultResponseCode = '202';
\r
931 else if(responses['203']) {
\r
932 response = responses['203'];
\r
933 defaultResponseCode = '203';
\r
935 else if(responses['204']) {
\r
936 response = responses['204'];
\r
937 defaultResponseCode = '204';
\r
939 else if(responses['205']) {
\r
940 response = responses['205'];
\r
941 defaultResponseCode = '205';
\r
943 else if(responses['206']) {
\r
944 response = responses['206'];
\r
945 defaultResponseCode = '206';
\r
947 else if(responses['default']) {
\r
948 response = responses['default'];
\r
949 defaultResponseCode = 'default';
\r
952 if(response && response.schema) {
\r
953 var resolvedModel = this.resolveModel(response.schema, definitions);
\r
954 delete responses[defaultResponseCode];
\r
955 if(resolvedModel) {
\r
956 this.successResponse = {};
\r
957 this.successResponse[defaultResponseCode] = resolvedModel;
\r
960 this.successResponse = {};
\r
961 this.successResponse[defaultResponseCode] = response.schema.type;
\r
963 this.type = response;
\r
966 if (errors.length > 0) {
\r
967 if(this.resource && this.resource.api && this.resource.api.fail)
\r
968 this.resource.api.fail(errors);
\r
974 OperationGroup.prototype.sort = function(sorter) {
\r
978 Operation.prototype.getType = function (param) {
\r
979 var type = param.type;
\r
980 var format = param.format;
\r
981 var isArray = false;
\r
983 if(type === 'integer' && format === 'int32')
\r
985 else if(type === 'integer' && format === 'int64')
\r
987 else if(type === 'integer')
\r
989 else if(type === 'string') {
\r
990 if(format === 'date-time')
\r
992 else if(format === 'date')
\r
997 else if(type === 'number' && format === 'float')
\r
999 else if(type === 'number' && format === 'double')
\r
1001 else if(type === 'number')
\r
1003 else if(type === 'boolean')
\r
1005 else if(type === 'array') {
\r
1008 str = this.getType(param.items);
\r
1013 var schema = param.schema;
\r
1015 var ref = schema.$ref;
\r
1017 ref = simpleRef(ref);
\r
1024 return this.getType(schema);
\r
1032 Operation.prototype.resolveModel = function (schema, definitions) {
\r
1033 if(typeof schema.$ref !== 'undefined') {
\r
1034 var ref = schema.$ref;
\r
1035 if(ref.indexOf('#/definitions/') === 0)
\r
1036 ref = ref.substring('#/definitions/'.length);
\r
1037 if(definitions[ref]) {
\r
1038 return new Model(ref, definitions[ref]);
\r
1041 if(schema.type === 'array')
\r
1042 return new ArrayModel(schema);
\r
1047 Operation.prototype.help = function(dontPrint) {
\r
1048 var out = this.nickname + ': ' + this.summary + '\n';
\r
1049 for(var i = 0; i < this.parameters.length; i++) {
\r
1050 var param = this.parameters[i];
\r
1051 var typeInfo = param.signature;
\r
1052 out += '\n * ' + param.name + ' (' + typeInfo + '): ' + param.description;
\r
1054 if(typeof dontPrint === 'undefined')
\r
1059 Operation.prototype.getModelSignature = function(type, definitions) {
\r
1060 var isPrimitive, listType;
\r
1062 if(type instanceof Array) {
\r
1066 else if(typeof type === 'undefined')
\r
1067 type = 'undefined';
\r
1069 if(type === 'string')
\r
1070 isPrimitive = true;
\r
1072 isPrimitive = (listType && definitions[listType]) || (definitions[type]) ? false : true;
\r
1073 if (isPrimitive) {
\r
1075 return 'Array[' + type + ']';
\r
1077 return type.toString();
\r
1080 return 'Array[' + definitions[type].getMockSignature() + ']';
\r
1082 return definitions[type].getMockSignature();
\r
1086 Operation.prototype.supportHeaderParams = function () {
\r
1090 Operation.prototype.supportedSubmitMethods = function () {
\r
1091 return this.parent.supportedSubmitMethods;
\r
1094 Operation.prototype.getHeaderParams = function (args) {
\r
1095 var headers = this.setContentTypes(args, {});
\r
1096 for(var i = 0; i < this.parameters.length; i++) {
\r
1097 var param = this.parameters[i];
\r
1098 if(typeof args[param.name] !== 'undefined') {
\r
1099 if (param.in === 'header') {
\r
1100 var value = args[param.name];
\r
1101 if(Array.isArray(value))
\r
1102 value = value.toString();
\r
1103 headers[param.name] = value;
\r
1110 Operation.prototype.urlify = function (args) {
\r
1111 var formParams = {};
\r
1112 var requestUrl = this.path;
\r
1114 // grab params from the args, build the querystring along the way
\r
1115 var querystring = '';
\r
1116 for(var i = 0; i < this.parameters.length; i++) {
\r
1117 var param = this.parameters[i];
\r
1118 if(typeof args[param.name] !== 'undefined') {
\r
1119 if(param.in === 'path') {
\r
1120 var reg = new RegExp('\{' + param.name + '\}', 'gi');
\r
1121 var value = args[param.name];
\r
1122 if(Array.isArray(value))
\r
1123 value = this.encodePathCollection(param.collectionFormat, param.name, value);
\r
1125 value = this.encodePathParam(value);
\r
1126 requestUrl = requestUrl.replace(reg, value);
\r
1128 else if (param.in === 'query' && typeof args[param.name] !== 'undefined') {
\r
1129 if(querystring === '')
\r
1130 querystring += '?';
\r
1132 querystring += '&';
\r
1133 if(typeof param.collectionFormat !== 'undefined') {
\r
1134 var qp = args[param.name];
\r
1135 if(Array.isArray(qp))
\r
1136 querystring += this.encodeQueryCollection(param.collectionFormat, param.name, qp);
\r
1138 querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
\r
1141 querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
\r
1143 else if (param.in === 'formData')
\r
1144 formParams[param.name] = args[param.name];
\r
1147 var url = this.scheme + '://' + this.host;
\r
1149 if(this.basePath !== '/')
\r
1150 url += this.basePath;
\r
1152 return url + requestUrl + querystring;
\r
1155 Operation.prototype.getMissingParams = function(args) {
\r
1156 var missingParams = [];
\r
1157 // check required params, track the ones that are missing
\r
1159 for(i = 0; i < this.parameters.length; i++) {
\r
1160 var param = this.parameters[i];
\r
1161 if(param.required === true) {
\r
1162 if(typeof args[param.name] === 'undefined')
\r
1163 missingParams = param.name;
\r
1166 return missingParams;
\r
1169 Operation.prototype.getBody = function(headers, args, opts) {
\r
1170 var formParams = {}, body, key;
\r
1172 for(var i = 0; i < this.parameters.length; i++) {
\r
1173 var param = this.parameters[i];
\r
1174 if(typeof args[param.name] !== 'undefined') {
\r
1175 if (param.in === 'body') {
\r
1176 body = args[param.name];
\r
1177 } else if(param.in === 'formData') {
\r
1178 formParams[param.name] = args[param.name];
\r
1183 // handle form params
\r
1184 if(headers['Content-Type'] === 'application/x-www-form-urlencoded') {
\r
1186 for(key in formParams) {
\r
1187 value = formParams[key];
\r
1188 if(typeof value !== 'undefined'){
\r
1189 if(encoded !== "")
\r
1191 encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
\r
1196 else if (headers['Content-Type'] && headers['Content-Type'].indexOf('multipart/form-data') >= 0) {
\r
1197 if(opts.useJQuery) {
\r
1198 var bodyParam = new FormData();
\r
1199 bodyParam.type = 'formData';
\r
1200 for (key in formParams) {
\r
1201 value = args[key];
\r
1202 if (typeof value !== 'undefined') {
\r
1203 // required for jquery file upload
\r
1204 if(value.type === 'file' && value.value) {
\r
1205 delete headers['Content-Type'];
\r
1206 bodyParam.append(key, value.value);
\r
1209 bodyParam.append(key, value);
\r
1220 * gets sample response for a single operation
\r
1222 Operation.prototype.getModelSampleJSON = function(type, models) {
\r
1223 var isPrimitive, listType, sampleJson;
\r
1225 listType = (type instanceof Array);
\r
1226 isPrimitive = models[type] ? false : true;
\r
1227 sampleJson = isPrimitive ? void 0 : models[type].createJSONSample();
\r
1229 sampleJson = listType ? [sampleJson] : sampleJson;
\r
1230 if(typeof sampleJson == 'string')
\r
1231 return sampleJson;
\r
1232 else if(typeof sampleJson === 'object') {
\r
1233 var t = sampleJson;
\r
1234 if(sampleJson instanceof Array && sampleJson.length > 0) {
\r
1235 t = sampleJson[0];
\r
1238 var xmlString = new XMLSerializer().serializeToString(t);
\r
1239 return this.formatXml(xmlString);
\r
1242 return JSON.stringify(sampleJson, null, 2);
\r
1245 return sampleJson;
\r
1252 Operation.prototype["do"] = function(args, opts, callback, error, parent) {
\r
1253 return this.execute(args, opts, callback, error, parent);
\r
1258 * executes an operation
\r
1260 Operation.prototype.execute = function(arg1, arg2, arg3, arg4, parent) {
\r
1261 var args = arg1 || {};
\r
1262 var opts = {}, success, error;
\r
1263 if(typeof arg2 === 'object') {
\r
1269 if(typeof arg2 === 'function') {
\r
1274 success = (success||log);
\r
1275 error = (error||log);
\r
1277 if(opts.useJQuery)
\r
1278 this.useJQuery = opts.useJQuery;
\r
1280 var missingParams = this.getMissingParams(args);
\r
1281 if(missingParams.length > 0) {
\r
1282 var message = 'missing required params: ' + missingParams;
\r
1286 var allHeaders = this.getHeaderParams(args);
\r
1287 var contentTypeHeaders = this.setContentTypes(args, opts);
\r
1289 var headers = {}, attrname;
\r
1290 for (attrname in allHeaders) { headers[attrname] = allHeaders[attrname]; }
\r
1291 for (attrname in contentTypeHeaders) { headers[attrname] = contentTypeHeaders[attrname]; }
\r
1293 var body = this.getBody(headers, args, opts);
\r
1294 var url = this.urlify(args);
\r
1298 method: this.method.toUpperCase(),
\r
1300 useJQuery: this.useJQuery,
\r
1303 response: function(response) {
\r
1304 return success(response, parent);
\r
1306 error: function(response) {
\r
1307 return error(response, parent);
\r
1311 var status = authorizations.apply(obj, this.operation.security);
\r
1312 if(opts.mock === true)
\r
1315 new SwaggerHttp().execute(obj, opts);
\r
1318 Operation.prototype.setContentTypes = function(args, opts) {
\r
1320 var accepts = 'application/json';
\r
1321 var consumes = args.parameterContentType || 'application/json';
\r
1322 var allDefinedParams = this.parameters;
\r
1323 var definedFormParams = [];
\r
1324 var definedFileParams = [];
\r
1328 // get params from the operation and set them in definedFileParams, definedFormParams, headers
\r
1330 for(i = 0; i < allDefinedParams.length; i++) {
\r
1331 var param = allDefinedParams[i];
\r
1332 if(param.in === 'formData') {
\r
1333 if(param.type === 'file')
\r
1334 definedFileParams.push(param);
\r
1336 definedFormParams.push(param);
\r
1338 else if(param.in === 'header' && opts) {
\r
1339 var key = param.name;
\r
1340 var headerValue = opts[param.name];
\r
1341 if(typeof opts[param.name] !== 'undefined')
\r
1342 headers[key] = headerValue;
\r
1344 else if(param.in === 'body' && typeof args[param.name] !== 'undefined') {
\r
1345 body = args[param.name];
\r
1349 // if there's a body, need to set the consumes header via requestContentType
\r
1350 if (body && (this.method === 'post' || this.method === 'put' || this.method === 'patch' || this.method === 'delete')) {
\r
1351 if (opts.requestContentType)
\r
1352 consumes = opts.requestContentType;
\r
1354 // if any form params, content type must be set
\r
1355 if(definedFormParams.length > 0) {
\r
1356 if(opts.requestContentType) // override if set
\r
1357 consumes = opts.requestContentType;
\r
1358 else if(definedFileParams.length > 0) // if a file, must be multipart/form-data
\r
1359 consumes = 'multipart/form-data';
\r
1360 else // default to x-www-from-urlencoded
\r
1361 consumes = 'application/x-www-form-urlencoded';
\r
1363 else if (this.type == 'DELETE')
\r
1365 else if (this.type != 'DELETE')
\r
1369 if (consumes && this.consumes) {
\r
1370 if (this.consumes.indexOf(consumes) === -1) {
\r
1371 log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.consumes));
\r
1375 if (opts.responseContentType) {
\r
1376 accepts = opts.responseContentType;
\r
1378 accepts = 'application/json';
\r
1380 if (accepts && this.produces) {
\r
1381 if (this.produces.indexOf(accepts) === -1) {
\r
1382 log('server can\'t produce ' + accepts);
\r
1386 if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded'))
\r
1387 headers['Content-Type'] = consumes;
\r
1389 headers.Accept = accepts;
\r
1393 Operation.prototype.asCurl = function (args) {
\r
1394 var obj = this.execute(args, {mock: true});
\r
1395 authorizations.apply(obj);
\r
1397 results.push('-X ' + this.method.toUpperCase());
\r
1398 if (obj.headers) {
\r
1400 for (key in obj.headers)
\r
1401 results.push('--header "' + key + ': ' + obj.headers[key] + '"');
\r
1405 if(typeof obj.body === 'object')
\r
1406 body = JSON.stringify(obj.body);
\r
1409 results.push('-d "' + body.replace(/"/g, '\\"') + '"');
\r
1411 return 'curl ' + (results.join(' ')) + ' "' + obj.url + '"';
\r
1414 Operation.prototype.encodePathCollection = function(type, name, value) {
\r
1417 var separator = '';
\r
1418 if(type === 'ssv')
\r
1419 separator = '%20';
\r
1420 else if(type === 'tsv')
\r
1421 separator = '\\t';
\r
1422 else if(type === 'pipes')
\r
1427 for(i = 0; i < value.length; i++) {
\r
1429 encoded = this.encodeQueryParam(value[i]);
\r
1431 encoded += separator + this.encodeQueryParam(value[i]);
\r
1436 Operation.prototype.encodeQueryCollection = function(type, name, value) {
\r
1439 if(type === 'default' || type === 'multi') {
\r
1440 for(i = 0; i < value.length; i++) {
\r
1441 if(i > 0) encoded += '&';
\r
1442 encoded += this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
\r
1446 var separator = '';
\r
1447 if(type === 'csv')
\r
1449 else if(type === 'ssv')
\r
1450 separator = '%20';
\r
1451 else if(type === 'tsv')
\r
1452 separator = '\\t';
\r
1453 else if(type === 'pipes')
\r
1455 else if(type === 'brackets') {
\r
1456 for(i = 0; i < value.length; i++) {
\r
1459 encoded += this.encodeQueryParam(name) + '[]=' + this.encodeQueryParam(value[i]);
\r
1462 if(separator !== '') {
\r
1463 for(i = 0; i < value.length; i++) {
\r
1465 encoded = this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
\r
1467 encoded += separator + this.encodeQueryParam(value[i]);
\r
1474 Operation.prototype.encodeQueryParam = function(arg) {
\r
1475 return encodeURIComponent(arg);
\r
1479 * TODO revisit, might not want to leave '/'
\r
1481 Operation.prototype.encodePathParam = function(pathParam) {
\r
1482 var encParts, part, parts, i, len;
\r
1483 pathParam = pathParam.toString();
\r
1484 if (pathParam.indexOf('/') === -1) {
\r
1485 return encodeURIComponent(pathParam);
\r
1487 parts = pathParam.split('/');
\r
1489 for (i = 0, len = parts.length; i < len; i++) {
\r
1490 encParts.push(encodeURIComponent(parts[i]));
\r
1492 return encParts.join('/');
\r
1496 var Model = function(name, definition) {
\r
1498 this.definition = definition || {};
\r
1499 this.properties = [];
\r
1500 var requiredFields = definition.required || [];
\r
1501 if(definition.type === 'array') {
\r
1502 var out = new ArrayModel(definition);
\r
1506 var props = definition.properties;
\r
1508 for(key in props) {
\r
1509 var required = false;
\r
1510 var property = props[key];
\r
1511 if(requiredFields.indexOf(key) >= 0)
\r
1513 this.properties.push(new Property(key, property, required));
\r
1518 Model.prototype.createJSONSample = function(modelsToIgnore) {
\r
1519 var i, result = {}, representations = {};
\r
1520 modelsToIgnore = (modelsToIgnore||{});
\r
1521 modelsToIgnore[this.name] = this;
\r
1522 for (i = 0; i < this.properties.length; i++) {
\r
1523 prop = this.properties[i];
\r
1524 var sample = prop.getSampleValue(modelsToIgnore, representations);
\r
1525 result[prop.name] = sample;
\r
1527 delete modelsToIgnore[this.name];
\r
1531 Model.prototype.getSampleValue = function(modelsToIgnore) {
\r
1532 var i, obj = {}, representations = {};
\r
1533 for(i = 0; i < this.properties.length; i++ ) {
\r
1534 var property = this.properties[i];
\r
1535 obj[property.name] = property.sampleValue(false, modelsToIgnore, representations);
\r
1540 Model.prototype.getMockSignature = function(modelsToIgnore) {
\r
1541 var i, prop, propertiesStr = [];
\r
1542 for (i = 0; i < this.properties.length; i++) {
\r
1543 prop = this.properties[i];
\r
1544 propertiesStr.push(prop.toString());
\r
1546 var strong = '<span class="strong">';
\r
1547 var stronger = '<span class="stronger">';
\r
1548 var strongClose = '</span>';
\r
1549 var classOpen = strong + this.name + ' {' + strongClose;
\r
1550 var classClose = strong + '}' + strongClose;
\r
1551 var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
\r
1552 if (!modelsToIgnore)
\r
1553 modelsToIgnore = {};
\r
1555 modelsToIgnore[this.name] = this;
\r
1556 for (i = 0; i < this.properties.length; i++) {
\r
1557 prop = this.properties[i];
\r
1558 var ref = prop.$ref;
\r
1559 var model = models[ref];
\r
1560 if (model && typeof modelsToIgnore[model.name] === 'undefined') {
\r
1561 returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
\r
1567 var Property = function(name, obj, required) {
\r
1568 this.schema = obj;
\r
1569 this.required = required;
\r
1571 this.$ref = simpleRef(obj.$ref);
\r
1572 else if (obj.type === 'array' && obj.items) {
\r
1573 if(obj.items.$ref)
\r
1574 this.$ref = simpleRef(obj.items.$ref);
\r
1579 this.description = obj.description;
\r
1581 this.optional = true;
\r
1582 this.optional = !required;
\r
1583 this.default = obj.default || null;
\r
1584 this.example = obj.example !== undefined ? obj.example : null;
\r
1585 this.collectionFormat = obj.collectionFormat || null;
\r
1586 this.maximum = obj.maximum || null;
\r
1587 this.exclusiveMaximum = obj.exclusiveMaximum || null;
\r
1588 this.minimum = obj.minimum || null;
\r
1589 this.exclusiveMinimum = obj.exclusiveMinimum || null;
\r
1590 this.maxLength = obj.maxLength || null;
\r
1591 this.minLength = obj.minLength || null;
\r
1592 this.pattern = obj.pattern || null;
\r
1593 this.maxItems = obj.maxItems || null;
\r
1594 this.minItems = obj.minItems || null;
\r
1595 this.uniqueItems = obj.uniqueItems || null;
\r
1596 this['enum'] = obj['enum'] || null;
\r
1597 this.multipleOf = obj.multipleOf || null;
\r
1600 Property.prototype.getSampleValue = function (modelsToIgnore, representations) {
\r
1601 return this.sampleValue(false, modelsToIgnore, representations);
\r
1604 Property.prototype.isArray = function () {
\r
1605 var schema = this.schema;
\r
1606 if(schema.type === 'array')
\r
1612 Property.prototype.sampleValue = function(isArray, ignoredModels, representations) {
\r
1613 isArray = (isArray || this.isArray());
\r
1614 ignoredModels = (ignoredModels || {});
\r
1615 // representations = (representations || {});
\r
1617 var type = getStringSignature(this.obj, true);
\r
1621 var refModelName = simpleRef(this.$ref);
\r
1622 var refModel = models[refModelName];
\r
1623 if(typeof representations[type] !== 'undefined') {
\r
1624 return representations[type];
\r
1628 if(refModel && typeof ignoredModels[type] === 'undefined') {
\r
1629 ignoredModels[type] = this;
\r
1630 output = refModel.getSampleValue(ignoredModels, representations);
\r
1631 representations[type] = output;
\r
1634 output = (representations[type] || refModelName);
\r
1637 else if(this.example)
\r
1638 output = this.example;
\r
1639 else if(this.default)
\r
1640 output = this.default;
\r
1641 else if(type === 'date-time')
\r
1642 output = new Date().toISOString();
\r
1643 else if(type === 'date')
\r
1644 output = new Date().toISOString().split("T")[0];
\r
1645 else if(type === 'string')
\r
1646 output = 'string';
\r
1647 else if(type === 'integer')
\r
1649 else if(type === 'long')
\r
1651 else if(type === 'float')
\r
1653 else if(type === 'double')
\r
1655 else if(type === 'boolean')
\r
1659 ignoredModels[type] = output;
\r
1666 getStringSignature = function(obj, baseComponent) {
\r
1668 if(typeof obj.$ref !== 'undefined')
\r
1669 str += simpleRef(obj.$ref);
\r
1670 else if(typeof obj.type === 'undefined')
\r
1672 else if(obj.type === 'array') {
\r
1674 str += getStringSignature((obj.items || obj.$ref || {}));
\r
1677 str += getStringSignature((obj.items || obj.$ref || {}));
\r
1681 else if(obj.type === 'integer' && obj.format === 'int32')
\r
1683 else if(obj.type === 'integer' && obj.format === 'int64')
\r
1685 else if(obj.type === 'integer' && typeof obj.format === 'undefined')
\r
1687 else if(obj.type === 'string' && obj.format === 'date-time')
\r
1688 str += 'date-time';
\r
1689 else if(obj.type === 'string' && obj.format === 'date')
\r
1691 else if(obj.type === 'string' && typeof obj.format === 'undefined')
\r
1693 else if(obj.type === 'number' && obj.format === 'float')
\r
1695 else if(obj.type === 'number' && obj.format === 'double')
\r
1697 else if(obj.type === 'number' && typeof obj.format === 'undefined')
\r
1699 else if(obj.type === 'boolean')
\r
1702 str += simpleRef(obj.$ref);
\r
1708 simpleRef = function(name) {
\r
1709 if(typeof name === 'undefined')
\r
1711 if(name.indexOf("#/definitions/") === 0)
\r
1712 return name.substring('#/definitions/'.length);
\r
1717 Property.prototype.toString = function() {
\r
1718 var str = getStringSignature(this.obj);
\r
1720 str = '<span class="propName ' + this.required + '">' + this.name + '</span> (<span class="propType">' + str + '</span>';
\r
1721 if(!this.required)
\r
1722 str += ', <span class="propOptKey">optional</span>';
\r
1726 str = this.name + ' (' + JSON.stringify(this.obj) + ')';
\r
1728 if(typeof this.description !== 'undefined')
\r
1729 str += ': ' + this.description;
\r
1731 if (this['enum']) {
\r
1732 str += ' = <span class="propVals">[\'' + this['enum'].join('\' or \'') + '\']</span>';
\r
1735 str += ': <span class="propDesc">' + this.descr + '</span>';
\r
1739 var options = '';
\r
1740 var isArray = this.schema.type === 'array';
\r
1744 if(this.schema.items)
\r
1745 type = this.schema.items.type;
\r
1750 type = this.schema.type;
\r
1754 options += optionHtml('Default', this.default);
\r
1758 if (this.minLength)
\r
1759 options += optionHtml('Min. Length', this.minLength);
\r
1760 if (this.maxLength)
\r
1761 options += optionHtml('Max. Length', this.maxLength);
\r
1763 options += optionHtml('Reg. Exp.', this.pattern);
\r
1768 options += optionHtml('Min. Value', this.minimum);
\r
1769 if (this.exclusiveMinimum)
\r
1770 options += optionHtml('Exclusive Min.', "true");
\r
1772 options += optionHtml('Max. Value', this.maximum);
\r
1773 if (this.exclusiveMaximum)
\r
1774 options += optionHtml('Exclusive Max.', "true");
\r
1775 if (this.multipleOf)
\r
1776 options += optionHtml('Multiple Of', this.multipleOf);
\r
1781 if (this.minItems)
\r
1782 options += optionHtml('Min. Items', this.minItems);
\r
1783 if (this.maxItems)
\r
1784 options += optionHtml('Max. Items', this.maxItems);
\r
1785 if (this.uniqueItems)
\r
1786 options += optionHtml('Unique Items', "true");
\r
1787 if (this.collectionFormat)
\r
1788 options += optionHtml('Coll. Format', this.collectionFormat);
\r
1791 if (this['enum']) {
\r
1794 if (type === 'number' || type === 'integer')
\r
1795 enumString = this['enum'].join(', ');
\r
1797 enumString = '"' + this['enum'].join('", "') + '"';
\r
1800 options += optionHtml('Enum', enumString);
\r
1803 if (options.length > 0)
\r
1804 str = '<span class="propWrap">' + str + '<table class="optionsWrapper"><tr><th colspan="2">' + this.name + '</th></tr>' + options + '</table></span>';
\r
1809 optionHtml = function(label, value) {
\r
1810 return '<tr><td class="optionName">' + label + ':</td><td>' + value + '</td></tr>';
\r
1813 typeFromJsonSchema = function(type, format) {
\r
1815 if(type === 'integer' && format === 'int32')
\r
1817 else if(type === 'integer' && format === 'int64')
\r
1819 else if(type === 'integer' && typeof format === 'undefined')
\r
1821 else if(type === 'string' && format === 'date-time')
\r
1822 str = 'date-time';
\r
1823 else if(type === 'string' && format === 'date')
\r
1825 else if(type === 'number' && format === 'float')
\r
1827 else if(type === 'number' && format === 'double')
\r
1829 else if(type === 'number' && typeof format === 'undefined')
\r
1831 else if(type === 'boolean')
\r
1833 else if(type === 'string')
\r
1839 var sampleModels = {};
\r
1843 SwaggerClient.prototype.buildFrom1_2Spec = function (response) {
\r
1844 if (response.apiVersion !== null) {
\r
1845 this.apiVersion = response.apiVersion;
\r
1848 this.apisArray = [];
\r
1849 this.consumes = response.consumes;
\r
1850 this.produces = response.produces;
\r
1851 this.authSchemes = response.authorizations;
\r
1852 this.info = this.convertInfo(response.info);
\r
1854 var isApi = false, i, res;
\r
1855 for (i = 0; i < response.apis.length; i++) {
\r
1856 var api = response.apis[i];
\r
1857 if (api.operations) {
\r
1859 for (j = 0; j < api.operations.length; j++) {
\r
1860 operation = api.operations[j];
\r
1865 if (response.basePath)
\r
1866 this.basePath = response.basePath;
\r
1867 else if (this.url.indexOf('?') > 0)
\r
1868 this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
\r
1870 this.basePath = this.url;
\r
1873 var newName = response.resourcePath.replace(/\//g, '');
\r
1874 this.resourcePath = response.resourcePath;
\r
1875 res = new SwaggerResource(response, this);
\r
1876 this.apis[newName] = res;
\r
1877 this.apisArray.push(res);
\r
1881 this.expectedResourceCount = response.apis.length;
\r
1882 for (k = 0; k < response.apis.length; k++) {
\r
1883 var resource = response.apis[k];
\r
1884 res = new SwaggerResource(resource, this);
\r
1885 this.apis[res.name] = res;
\r
1886 this.apisArray.push(res);
\r
1889 this.isValid = true;
\r
1893 SwaggerClient.prototype.finish = function() {
\r
1894 if (typeof this.success === 'function') {
\r
1895 this.isValid = true;
\r
1896 this.ready = true;
\r
1897 this.isBuilt = true;
\r
1898 this.selfReflect();
\r
1903 SwaggerClient.prototype.buildFrom1_1Spec = function (response) {
\r
1904 log('This API is using a deprecated version of Swagger! Please see http://github.com/wordnik/swagger-core/wiki for more info');
\r
1905 if (response.apiVersion !== null)
\r
1906 this.apiVersion = response.apiVersion;
\r
1908 this.apisArray = [];
\r
1909 this.produces = response.produces;
\r
1910 this.info = this.convertInfo(response.info);
\r
1911 var isApi = false, res;
\r
1912 for (var i = 0; i < response.apis.length; i++) {
\r
1913 var api = response.apis[i];
\r
1914 if (api.operations) {
\r
1915 for (var j = 0; j < api.operations.length; j++) {
\r
1916 operation = api.operations[j];
\r
1921 if (response.basePath) {
\r
1922 this.basePath = response.basePath;
\r
1923 } else if (this.url.indexOf('?') > 0) {
\r
1924 this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
\r
1926 this.basePath = this.url;
\r
1929 var newName = response.resourcePath.replace(/\//g, '');
\r
1930 this.resourcePath = response.resourcePath;
\r
1931 res = new SwaggerResource(response, this);
\r
1932 this.apis[newName] = res;
\r
1933 this.apisArray.push(res);
\r
1936 this.expectedResourceCount = response.apis.length;
\r
1937 for (k = 0; k < response.apis.length; k++) {
\r
1938 resource = response.apis[k];
\r
1939 res = new SwaggerResource(resource, this);
\r
1940 this.apis[res.name] = res;
\r
1941 this.apisArray.push(res);
\r
1944 this.isValid = true;
\r
1948 SwaggerClient.prototype.convertInfo = function (resp) {
\r
1949 if(typeof resp == 'object') {
\r
1952 info.title = resp.title;
\r
1953 info.description = resp.description;
\r
1954 info.termsOfService = resp.termsOfServiceUrl;
\r
1955 info.contact = {};
\r
1956 info.contact.name = resp.contact;
\r
1957 info.license = {};
\r
1958 info.license.name = resp.license;
\r
1959 info.license.url = resp.licenseUrl;
\r
1965 SwaggerClient.prototype.selfReflect = function () {
\r
1966 var resource, tag, ref;
\r
1967 if (this.apis === null) {
\r
1971 for (tag in ref) {
\r
1973 if (api.ready === null) {
\r
1977 this[tag].help = __bind(api.help, api);
\r
1979 this.setConsolidatedModels();
\r
1980 this.ready = true;
\r
1983 SwaggerClient.prototype.setConsolidatedModels = function () {
\r
1984 var model, modelName, resource, resource_name, i, apis, models, results;
\r
1987 for (resource_name in apis) {
\r
1988 resource = apis[resource_name];
\r
1989 for (modelName in resource.models) {
\r
1990 if (typeof this.models[modelName] === 'undefined') {
\r
1991 this.models[modelName] = resource.models[modelName];
\r
1992 this.modelsArray.push(resource.models[modelName]);
\r
1996 models = this.modelsArray;
\r
1998 for (i = 0; i < models.length; i++) {
\r
1999 model = models[i];
\r
2000 results.push(model.setReferencedModels(this.models));
\r
2005 var SwaggerResource = function (resourceObj, api) {
\r
2008 this.swaggerRequstHeaders = api.swaggerRequstHeaders;
\r
2009 this.path = (typeof this.api.resourcePath === 'string') ? this.api.resourcePath : resourceObj.path;
\r
2010 this.description = resourceObj.description;
\r
2011 this.authorizations = (resourceObj.authorizations || {});
\r
2013 var parts = this.path.split('/');
\r
2014 this.name = parts[parts.length - 1].replace('.{format}', '');
\r
2015 this.basePath = this.api.basePath;
\r
2016 this.operations = {};
\r
2017 this.operationsArray = [];
\r
2018 this.modelsArray = [];
\r
2019 this.models = api.models || {};
\r
2020 this.rawModels = {};
\r
2021 this.useJQuery = (typeof api.useJQuery !== 'undefined') ? api.useJQuery : null;
\r
2023 if ((resourceObj.apis) && this.api.resourcePath) {
\r
2024 this.addApiDeclaration(resourceObj);
\r
2026 if (typeof this.path === 'undefined') {
\r
2027 this.api.fail('SwaggerResources must have a path.');
\r
2029 if (this.path.substring(0, 4) === 'http') {
\r
2030 this.url = this.path.replace('{format}', 'json');
\r
2032 this.url = this.api.basePath + this.path.replace('{format}', 'json');
\r
2034 this.api.progress('fetching resource ' + this.name + ': ' + this.url);
\r
2038 useJQuery: this.useJQuery,
\r
2040 accept: this.swaggerRequstHeaders
\r
2043 response: function (resp) {
\r
2044 var responseObj = resp.obj || JSON.parse(resp.data);
\r
2045 _this.api.resourceCount += 1;
\r
2046 return _this.addApiDeclaration(responseObj);
\r
2048 error: function (response) {
\r
2049 _this.api.resourceCount += 1;
\r
2050 return _this.api.fail('Unable to read api \'' +
\r
2051 _this.name + '\' from path ' + _this.url + ' (server returned ' + response.statusText + ')');
\r
2055 var e = typeof window !== 'undefined' ? window : exports;
\r
2056 e.authorizations.apply(obj);
\r
2057 new SwaggerHttp().execute(obj);
\r
2061 SwaggerResource.prototype.help = function (dontPrint) {
\r
2063 var output = 'operations for the "' + this.name + '" tag';
\r
2064 for(i = 0; i < this.operationsArray.length; i++) {
\r
2065 var api = this.operationsArray[i];
\r
2066 output += '\n * ' + api.nickname + ': ' + api.description;
\r
2076 SwaggerResource.prototype.getAbsoluteBasePath = function (relativeBasePath) {
\r
2078 url = this.api.basePath;
\r
2079 pos = url.lastIndexOf(relativeBasePath);
\r
2080 var parts = url.split('/');
\r
2081 var rootUrl = parts[0] + '//' + parts[2];
\r
2083 if (relativeBasePath.indexOf('http') === 0)
\r
2084 return relativeBasePath;
\r
2085 if (relativeBasePath === '/')
\r
2087 if (relativeBasePath.substring(0, 1) == '/') {
\r
2088 // use root + relative
\r
2089 return rootUrl + relativeBasePath;
\r
2092 pos = this.basePath.lastIndexOf('/');
\r
2093 var base = this.basePath.substring(0, pos);
\r
2094 if (base.substring(base.length - 1) == '/')
\r
2095 return base + relativeBasePath;
\r
2097 return base + '/' + relativeBasePath;
\r
2101 SwaggerResource.prototype.addApiDeclaration = function (response) {
\r
2102 if (typeof response.produces === 'string')
\r
2103 this.produces = response.produces;
\r
2104 if (typeof response.consumes === 'string')
\r
2105 this.consumes = response.consumes;
\r
2106 if ((typeof response.basePath === 'string') && response.basePath.replace(/\s/g, '').length > 0)
\r
2107 this.basePath = response.basePath.indexOf('http') === -1 ? this.getAbsoluteBasePath(response.basePath) : response.basePath;
\r
2108 this.resourcePath = response.resourcePath;
\r
2109 this.addModels(response.models);
\r
2110 if (response.apis) {
\r
2111 for (var i = 0 ; i < response.apis.length; i++) {
\r
2112 var endpoint = response.apis[i];
\r
2113 this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces);
\r
2116 this.api[this.name] = this;
\r
2117 this.ready = true;
\r
2118 if(this.api.resourceCount === this.api.expectedResourceCount)
\r
2119 this.api.finish();
\r
2123 SwaggerResource.prototype.addModels = function (models) {
\r
2124 if (typeof models === 'object') {
\r
2126 for (modelName in models) {
\r
2127 if (typeof this.models[modelName] === 'undefined') {
\r
2128 var swaggerModel = new SwaggerModel(modelName, models[modelName]);
\r
2129 this.modelsArray.push(swaggerModel);
\r
2130 this.models[modelName] = swaggerModel;
\r
2131 this.rawModels[modelName] = models[modelName];
\r
2135 for (var i = 0; i < this.modelsArray.length; i++) {
\r
2136 var model = this.modelsArray[i];
\r
2137 output.push(model.setReferencedModels(this.models));
\r
2143 SwaggerResource.prototype.addOperations = function (resource_path, ops, consumes, produces) {
\r
2146 for (var i = 0; i < ops.length; i++) {
\r
2148 consumes = this.consumes;
\r
2149 produces = this.produces;
\r
2150 if (typeof o.consumes !== 'undefined')
\r
2151 consumes = o.consumes;
\r
2153 consumes = this.consumes;
\r
2155 if (typeof o.produces !== 'undefined')
\r
2156 produces = o.produces;
\r
2158 produces = this.produces;
\r
2159 var type = (o.type || o.responseClass);
\r
2161 if (type === 'array') {
\r
2164 ref = o.items.type || o.items.$ref;
\r
2165 type = 'array[' + ref + ']';
\r
2167 var responseMessages = o.responseMessages;
\r
2168 var method = o.method;
\r
2169 if (o.httpMethod) {
\r
2170 method = o.httpMethod;
\r
2172 if (o.supportedContentTypes) {
\r
2173 consumes = o.supportedContentTypes;
\r
2175 if (o.errorResponses) {
\r
2176 responseMessages = o.errorResponses;
\r
2177 for (var j = 0; j < responseMessages.length; j++) {
\r
2178 r = responseMessages[j];
\r
2179 r.message = r.reason;
\r
2183 o.nickname = this.sanitize(o.nickname);
\r
2184 var op = new SwaggerOperation(o.nickname,
\r
2191 responseMessages,
\r
2195 o.authorizations,
\r
2198 this.operations[op.nickname] = op;
\r
2199 output.push(this.operationsArray.push(op));
\r
2205 SwaggerResource.prototype.sanitize = function (nickname) {
\r
2207 op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|.\/?,\\'""-]/g, '_');
\r
2208 op = op.replace(/((_){2,})/g, '_');
\r
2209 op = op.replace(/^(_)*/g, '');
\r
2210 op = op.replace(/([_])*$/g, '');
\r
2214 var SwaggerModel = function (modelName, obj) {
\r
2215 this.name = typeof obj.id !== 'undefined' ? obj.id : modelName;
\r
2216 this.properties = [];
\r
2218 for (propertyName in obj.properties) {
\r
2219 if (obj.required) {
\r
2221 for (value in obj.required) {
\r
2222 if (propertyName === obj.required[value]) {
\r
2223 obj.properties[propertyName].required = true;
\r
2227 var prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName], this);
\r
2228 this.properties.push(prop);
\r
2232 SwaggerModel.prototype.setReferencedModels = function (allModels) {
\r
2234 for (var i = 0; i < this.properties.length; i++) {
\r
2235 var property = this.properties[i];
\r
2236 var type = property.type || property.dataType;
\r
2237 if (allModels[type])
\r
2238 results.push(property.refModel = allModels[type]);
\r
2239 else if ((property.refDataType) && (allModels[property.refDataType]))
\r
2240 results.push(property.refModel = allModels[property.refDataType]);
\r
2242 results.push(void 0);
\r
2247 SwaggerModel.prototype.getMockSignature = function (modelsToIgnore) {
\r
2248 var i, prop, propertiesStr = [];
\r
2249 for (i = 0; i < this.properties.length; i++) {
\r
2250 prop = this.properties[i];
\r
2251 propertiesStr.push(prop.toString());
\r
2254 var strong = '<span class="strong">';
\r
2255 var strongClose = '</span>';
\r
2256 var classOpen = strong + this.name + ' {' + strongClose;
\r
2257 var classClose = strong + '}' + strongClose;
\r
2258 var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
\r
2259 if (!modelsToIgnore)
\r
2260 modelsToIgnore = [];
\r
2261 modelsToIgnore.push(this.name);
\r
2263 for (i = 0; i < this.properties.length; i++) {
\r
2264 prop = this.properties[i];
\r
2265 if ((prop.refModel) && modelsToIgnore.indexOf(prop.refModel.name) === -1) {
\r
2266 returnVal = returnVal + ('<br>' + prop.refModel.getMockSignature(modelsToIgnore));
\r
2272 SwaggerModel.prototype.createJSONSample = function (modelsToIgnore) {
\r
2273 if (sampleModels[this.name]) {
\r
2274 return sampleModels[this.name];
\r
2278 modelsToIgnore = (modelsToIgnore || []);
\r
2279 modelsToIgnore.push(this.name);
\r
2280 for (var i = 0; i < this.properties.length; i++) {
\r
2281 var prop = this.properties[i];
\r
2282 result[prop.name] = prop.getSampleValue(modelsToIgnore);
\r
2284 modelsToIgnore.pop(this.name);
\r
2289 var SwaggerModelProperty = function (name, obj, model) {
\r
2291 this.dataType = obj.type || obj.dataType || obj.$ref;
\r
2292 this.isCollection = this.dataType && (this.dataType.toLowerCase() === 'array' || this.dataType.toLowerCase() === 'list' || this.dataType.toLowerCase() === 'set');
\r
2293 this.descr = obj.description;
\r
2294 this.required = obj.required;
\r
2295 this.defaultValue = applyModelPropertyMacro(obj, model);
\r
2297 if (obj.items.type) {
\r
2298 this.refDataType = obj.items.type;
\r
2300 if (obj.items.$ref) {
\r
2301 this.refDataType = obj.items.$ref;
\r
2304 this.dataTypeWithRef = this.refDataType ? (this.dataType + '[' + this.refDataType + ']') : this.dataType;
\r
2305 if (obj.allowableValues) {
\r
2306 this.valueType = obj.allowableValues.valueType;
\r
2307 this.values = obj.allowableValues.values;
\r
2308 if (this.values) {
\r
2309 this.valuesString = '\'' + this.values.join('\' or \'') + '\'';
\r
2312 if (obj['enum']) {
\r
2313 this.valueType = 'string';
\r
2314 this.values = obj['enum'];
\r
2315 if (this.values) {
\r
2316 this.valueString = '\'' + this.values.join('\' or \'') + '\'';
\r
2321 SwaggerModelProperty.prototype.getSampleValue = function (modelsToIgnore) {
\r
2323 if ((this.refModel) && (modelsToIgnore.indexOf(this.refModel.name) === -1)) {
\r
2324 result = this.refModel.createJSONSample(modelsToIgnore);
\r
2326 if (this.isCollection) {
\r
2327 result = this.toSampleValue(this.refDataType);
\r
2329 result = this.toSampleValue(this.dataType);
\r
2332 if (this.isCollection) {
\r
2339 SwaggerModelProperty.prototype.toSampleValue = function (value) {
\r
2341 if ((typeof this.defaultValue !== 'undefined') && this.defaultValue) {
\r
2342 result = this.defaultValue;
\r
2343 } else if (value === 'integer') {
\r
2345 } else if (value === 'boolean') {
\r
2347 } else if (value === 'double' || value === 'number') {
\r
2349 } else if (value === 'string') {
\r
2357 SwaggerModelProperty.prototype.toString = function () {
\r
2358 var req = this.required ? 'propReq' : 'propOpt';
\r
2359 var str = '<span class="propName ' + req + '">' + this.name + '</span> (<span class="propType">' + this.dataTypeWithRef + '</span>';
\r
2360 if (!this.required) {
\r
2361 str += ', <span class="propOptKey">optional</span>';
\r
2364 if (this.values) {
\r
2365 str += ' = <span class="propVals">[\'' + this.values.join('\' or \'') + '\']</span>';
\r
2368 str += ': <span class="propDesc">' + this.descr + '</span>';
\r
2373 var SwaggerOperation = function (nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations, deprecated) {
\r
2377 this.nickname = (nickname || errors.push('SwaggerOperations must have a nickname.'));
\r
2378 this.path = (path || errors.push('SwaggerOperation ' + nickname + ' is missing path.'));
\r
2379 this.method = (method || errors.push('SwaggerOperation ' + nickname + ' is missing method.'));
\r
2380 this.parameters = parameters ? parameters : [];
\r
2381 this.summary = summary;
\r
2382 this.notes = notes;
\r
2384 this.responseMessages = (responseMessages || []);
\r
2385 this.resource = (resource || errors.push('Resource is required'));
\r
2386 this.consumes = consumes;
\r
2387 this.produces = produces;
\r
2388 this.authorizations = typeof authorizations !== 'undefined' ? authorizations : resource.authorizations;
\r
2389 this.deprecated = deprecated;
\r
2390 this['do'] = __bind(this['do'], this);
\r
2393 if(typeof this.deprecated === 'string') {
\r
2394 switch(this.deprecated.toLowerCase()) {
\r
2395 case 'true': case 'yes': case '1': {
\r
2396 this.deprecated = true;
\r
2399 case 'false': case 'no': case '0': case null: {
\r
2400 this.deprecated = false;
\r
2403 default: this.deprecated = Boolean(this.deprecated);
\r
2407 if (errors.length > 0) {
\r
2408 console.error('SwaggerOperation errors', errors, arguments);
\r
2409 this.resource.api.fail(errors);
\r
2412 this.path = this.path.replace('{format}', 'json');
\r
2413 this.method = this.method.toLowerCase();
\r
2414 this.isGetMethod = this.method === 'get';
\r
2417 this.resourceName = this.resource.name;
\r
2418 if (typeof this.type !== 'undefined' && this.type === 'void')
\r
2421 this.responseClassSignature = this.getSignature(this.type, this.resource.models);
\r
2422 this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models);
\r
2425 for (i = 0; i < this.parameters.length; i++) {
\r
2426 var param = this.parameters[i];
\r
2427 // might take this away
\r
2428 param.name = param.name || param.type || param.dataType;
\r
2429 // for 1.1 compatibility
\r
2430 type = param.type || param.dataType;
\r
2431 if (type === 'array') {
\r
2432 type = 'array[' + (param.items.$ref ? param.items.$ref : param.items.type) + ']';
\r
2434 param.type = type;
\r
2436 if (type && type.toLowerCase() === 'boolean') {
\r
2437 param.allowableValues = {};
\r
2438 param.allowableValues.values = ['true', 'false'];
\r
2440 param.signature = this.getSignature(type, this.resource.models);
\r
2441 param.sampleJSON = this.getSampleJSON(type, this.resource.models);
\r
2443 var enumValue = param['enum'];
\r
2444 if (typeof enumValue !== 'undefined') {
\r
2445 param.isList = true;
\r
2446 param.allowableValues = {};
\r
2447 param.allowableValues.descriptiveValues = [];
\r
2449 for (j = 0; j < enumValue.length; j++) {
\r
2451 if (param.defaultValue) {
\r
2452 param.allowableValues.descriptiveValues.push({
\r
2454 isDefault: (v === param.defaultValue)
\r
2458 param.allowableValues.descriptiveValues.push({
\r
2465 else if (param.allowableValues) {
\r
2466 if (param.allowableValues.valueType === 'RANGE')
\r
2467 param.isRange = true;
\r
2469 param.isList = true;
\r
2470 if (param.allowableValues) {
\r
2471 param.allowableValues.descriptiveValues = [];
\r
2472 if (param.allowableValues.values) {
\r
2473 for (j = 0; j < param.allowableValues.values.length; j++) {
\r
2474 v = param.allowableValues.values[j];
\r
2475 if (param.defaultValue !== null) {
\r
2476 param.allowableValues.descriptiveValues.push({
\r
2478 isDefault: (v === param.defaultValue)
\r
2482 param.allowableValues.descriptiveValues.push({
\r
2491 param.defaultValue = applyParameterMacro(this, param);
\r
2493 var defaultSuccessCallback = this.resource.api.defaultSuccessCallback || null;
\r
2494 var defaultErrorCallback = this.resource.api.defaultErrorCallback || null;
\r
2496 this.resource[this.nickname] = function (args, opts, callback, error) {
\r
2497 var arg1, arg2, arg3, arg4;
\r
2498 if(typeof args === 'function') { // right shift 3
\r
2499 arg1 = {}; arg2 = {}; arg3 = args; arg4 = opts;
\r
2501 else if(typeof args === 'object' && typeof opts === 'function') { // right shift 2
\r
2502 arg1 = args; arg2 = {}; arg3 = opts; arg4 = callback;
\r
2505 arg1 = args; arg2 = opts; arg3 = callback; arg4 = error;
\r
2507 return _this['do'](arg1 || {}, arg2 || {}, arg3 || defaultSuccessCallback, arg4 || defaultErrorCallback);
\r
2510 this.resource[this.nickname].help = function (dontPrint) {
\r
2511 return _this.help(dontPrint);
\r
2513 this.resource[this.nickname].asCurl = function (args) {
\r
2514 return _this.asCurl(args);
\r
2518 SwaggerOperation.prototype.isListType = function (type) {
\r
2519 if (type && type.indexOf('[') >= 0) {
\r
2520 return type.substring(type.indexOf('[') + 1, type.indexOf(']'));
\r
2526 SwaggerOperation.prototype.getSignature = function (type, models) {
\r
2527 var isPrimitive, listType;
\r
2528 listType = this.isListType(type);
\r
2529 isPrimitive = ((typeof listType !== 'undefined') && models[listType]) || (typeof models[type] !== 'undefined') ? false : true;
\r
2530 if (isPrimitive) {
\r
2533 if (typeof listType !== 'undefined') {
\r
2534 return models[listType].getMockSignature();
\r
2536 return models[type].getMockSignature();
\r
2541 SwaggerOperation.prototype.getSampleJSON = function (type, models) {
\r
2542 var isPrimitive, listType, val;
\r
2543 listType = this.isListType(type);
\r
2544 isPrimitive = ((typeof listType !== 'undefined') && models[listType]) || (typeof models[type] !== 'undefined') ? false : true;
\r
2545 val = isPrimitive ? void 0 : (listType ? models[listType].createJSONSample() : models[type].createJSONSample());
\r
2547 val = listType ? [val] : val;
\r
2548 if (typeof val == 'string')
\r
2550 else if (typeof val === 'object') {
\r
2552 if (val instanceof Array && val.length > 0) {
\r
2556 var xmlString = new XMLSerializer().serializeToString(t);
\r
2557 return this.formatXml(xmlString);
\r
2560 return JSON.stringify(val, null, 2);
\r
2567 SwaggerOperation.prototype['do'] = function (args, opts, callback, error) {
\r
2568 var key, param, params, possibleParams = [], req, value;
\r
2570 if (typeof error !== 'function') {
\r
2571 error = function (xhr, textStatus, error) {
\r
2572 return log(xhr, textStatus, error);
\r
2576 if (typeof callback !== 'function') {
\r
2577 callback = function (response) {
\r
2580 if (response !== null) {
\r
2581 content = response.data;
\r
2583 content = 'no data';
\r
2585 return log('default callback: ' + content);
\r
2590 params.headers = [];
\r
2591 if (args.headers) {
\r
2592 params.headers = args.headers;
\r
2593 delete args.headers;
\r
2595 // allow override from the opts
\r
2596 if(opts && opts.responseContentType) {
\r
2597 params.headers['Content-Type'] = opts.responseContentType;
\r
2599 if(opts && opts.requestContentType) {
\r
2600 params.headers.Accept = opts.requestContentType;
\r
2603 for (var i = 0; i < this.parameters.length; i++) {
\r
2604 param = this.parameters[i];
\r
2605 if (param.paramType === 'header') {
\r
2606 if (typeof args[param.name] !== 'undefined')
\r
2607 params.headers[param.name] = args[param.name];
\r
2609 else if (param.paramType === 'form' || param.paramType.toLowerCase() === 'file')
\r
2610 possibleParams.push(param);
\r
2611 else if (param.paramType === 'body' && param.name !== 'body' && typeof args[param.name] !== 'undefined') {
\r
2613 throw new Error('Saw two body params in an API listing; expecting a max of one.');
\r
2615 args.body = args[param.name];
\r
2619 if (typeof args.body !== 'undefined') {
\r
2620 params.body = args.body;
\r
2624 if (possibleParams) {
\r
2625 for (key in possibleParams) {
\r
2626 value = possibleParams[key];
\r
2627 if (args[value.name]) {
\r
2628 params[value.name] = args[value.name];
\r
2633 req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this);
\r
2641 SwaggerOperation.prototype.pathJson = function () {
\r
2642 return this.path.replace('{format}', 'json');
\r
2645 SwaggerOperation.prototype.pathXml = function () {
\r
2646 return this.path.replace('{format}', 'xml');
\r
2649 SwaggerOperation.prototype.encodePathParam = function (pathParam) {
\r
2650 var encParts, part, parts, _i, _len;
\r
2651 pathParam = pathParam.toString();
\r
2652 if (pathParam.indexOf('/') === -1) {
\r
2653 return encodeURIComponent(pathParam);
\r
2655 parts = pathParam.split('/');
\r
2657 for (_i = 0, _len = parts.length; _i < _len; _i++) {
\r
2659 encParts.push(encodeURIComponent(part));
\r
2661 return encParts.join('/');
\r
2665 SwaggerOperation.prototype.urlify = function (args) {
\r
2666 var i, j, param, url;
\r
2667 // ensure no double slashing...
\r
2668 if(this.resource.basePath.length > 1 && this.resource.basePath.slice(-1) === '/' && this.pathJson().charAt(0) === '/')
\r
2669 url = this.resource.basePath + this.pathJson().substring(1);
\r
2671 url = this.resource.basePath + this.pathJson();
\r
2672 var params = this.parameters;
\r
2673 for (i = 0; i < params.length; i++) {
\r
2674 param = params[i];
\r
2675 if (param.paramType === 'path') {
\r
2676 if (typeof args[param.name] !== 'undefined') {
\r
2677 // apply path params and remove from args
\r
2678 var reg = new RegExp('\\{\\s*?' + param.name + '[^\\{\\}\\/]*(?:\\{.*?\\}[^\\{\\}\\/]*)*\\}(?=(\\/?|$))', 'gi');
\r
2679 url = url.replace(reg, this.encodePathParam(args[param.name]));
\r
2680 delete args[param.name];
\r
2683 throw '' + param.name + ' is a required path param.';
\r
2687 var queryParams = '';
\r
2688 for (i = 0; i < params.length; i++) {
\r
2689 param = params[i];
\r
2690 if(param.paramType === 'query') {
\r
2691 if (queryParams !== '')
\r
2692 queryParams += '&';
\r
2693 if (Array.isArray(param)) {
\r
2695 for(j = 0; j < param.length; j++) {
\r
2698 output += encodeURIComponent(param[j]);
\r
2700 queryParams += encodeURIComponent(param.name) + '=' + output;
\r
2703 if (typeof args[param.name] !== 'undefined') {
\r
2704 queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]);
\r
2706 if (param.required)
\r
2707 throw '' + param.name + ' is a required query param.';
\r
2712 if ((queryParams) && queryParams.length > 0)
\r
2713 url += '?' + queryParams;
\r
2717 SwaggerOperation.prototype.supportHeaderParams = function () {
\r
2718 return this.resource.api.supportHeaderParams;
\r
2721 SwaggerOperation.prototype.supportedSubmitMethods = function () {
\r
2722 return this.resource.api.supportedSubmitMethods;
\r
2725 SwaggerOperation.prototype.getQueryParams = function (args) {
\r
2726 return this.getMatchingParams(['query'], args);
\r
2729 SwaggerOperation.prototype.getHeaderParams = function (args) {
\r
2730 return this.getMatchingParams(['header'], args);
\r
2733 SwaggerOperation.prototype.getMatchingParams = function (paramTypes, args) {
\r
2734 var matchingParams = {};
\r
2735 var params = this.parameters;
\r
2736 for (var i = 0; i < params.length; i++) {
\r
2737 param = params[i];
\r
2738 if (args && args[param.name])
\r
2739 matchingParams[param.name] = args[param.name];
\r
2741 var headers = this.resource.api.headers;
\r
2743 for (name in headers) {
\r
2744 var value = headers[name];
\r
2745 matchingParams[name] = value;
\r
2747 return matchingParams;
\r
2750 SwaggerOperation.prototype.help = function (dontPrint) {
\r
2751 var msg = this.nickname + ': ' + this.summary;
\r
2752 var params = this.parameters;
\r
2753 for (var i = 0; i < params.length; i++) {
\r
2754 var param = params[i];
\r
2755 msg += '\n* ' + param.name + (param.required ? ' (required)' : '') + " - " + param.description;
\r
2765 SwaggerOperation.prototype.asCurl = function (args) {
\r
2769 var headers = SwaggerRequest.prototype.setHeaders(args, {}, this);
\r
2770 for(i = 0; i < this.parameters.length; i++) {
\r
2771 var param = this.parameters[i];
\r
2772 if(param.paramType && param.paramType === 'header' && args[param.name]) {
\r
2773 headers[param.name] = args[param.name];
\r
2778 for (key in headers) {
\r
2779 results.push('--header "' + key + ': ' + headers[key] + '"');
\r
2781 return 'curl ' + (results.join(' ')) + ' ' + this.urlify(args);
\r
2784 SwaggerOperation.prototype.formatXml = function (xml) {
\r
2785 var contexp, formatted, indent, lastType, lines, ln, pad, reg, transitions, wsexp, _fn, _i, _len;
\r
2786 reg = /(>)(<)(\/*)/g;
\r
2787 wsexp = /[ ]*(.*)[ ]+\n/g;
\r
2788 contexp = /(<.+>)(.+\n)/g;
\r
2789 xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
\r
2792 lines = xml.split('\n');
\r
2794 lastType = 'other';
\r
2796 'single->single': 0,
\r
2797 'single->closing': -1,
\r
2798 'single->opening': 0,
\r
2799 'single->other': 0,
\r
2800 'closing->single': 0,
\r
2801 'closing->closing': -1,
\r
2802 'closing->opening': 0,
\r
2803 'closing->other': 0,
\r
2804 'opening->single': 1,
\r
2805 'opening->closing': 0,
\r
2806 'opening->opening': 1,
\r
2807 'opening->other': 1,
\r
2808 'other->single': 0,
\r
2809 'other->closing': -1,
\r
2810 'other->opening': 0,
\r
2813 _fn = function (ln) {
\r
2814 var fromTo, j, key, padding, type, types, value;
\r
2816 single: Boolean(ln.match(/<.+\/>/)),
\r
2817 closing: Boolean(ln.match(/<\/.+>/)),
\r
2818 opening: Boolean(ln.match(/<[^!?].*>/))
\r
2820 type = ((function () {
\r
2823 for (key in types) {
\r
2824 value = types[key];
\r
2826 _results.push(key);
\r
2831 type = type === void 0 ? 'other' : type;
\r
2832 fromTo = lastType + '->' + type;
\r
2835 indent += transitions[fromTo];
\r
2836 padding = ((function () {
\r
2837 var _j, _ref5, _results;
\r
2839 for (j = _j = 0, _ref5 = indent; 0 <= _ref5 ? _j < _ref5 : _j > _ref5; j = 0 <= _ref5 ? ++_j : --_j) {
\r
2840 _results.push(' ');
\r
2844 if (fromTo === 'opening->closing') {
\r
2845 formatted = formatted.substr(0, formatted.length - 1) + ln + '\n';
\r
2847 formatted += padding + ln + '\n';
\r
2850 for (_i = 0, _len = lines.length; _i < _len; _i++) {
\r
2857 var SwaggerRequest = function (type, url, params, opts, successCallback, errorCallback, operation, execution) {
\r
2861 this.useJQuery = (typeof operation.resource.useJQuery !== 'undefined' ? operation.resource.useJQuery : null);
\r
2862 this.type = (type || errors.push('SwaggerRequest type is required (get/post/put/delete/patch/options).'));
\r
2863 this.url = (url || errors.push('SwaggerRequest url is required.'));
\r
2864 this.params = params;
\r
2866 this.successCallback = (successCallback || errors.push('SwaggerRequest successCallback is required.'));
\r
2867 this.errorCallback = (errorCallback || errors.push('SwaggerRequest error callback is required.'));
\r
2868 this.operation = (operation || errors.push('SwaggerRequest operation is required.'));
\r
2869 this.execution = execution;
\r
2870 this.headers = (params.headers || {});
\r
2872 if (errors.length > 0) {
\r
2876 this.type = this.type.toUpperCase();
\r
2878 // set request, response content type headers
\r
2879 var headers = this.setHeaders(params, opts, this.operation);
\r
2880 var body = params.body;
\r
2882 // encode the body for form submits
\r
2883 if (headers['Content-Type']) {
\r
2884 var key, value, values = {}, i;
\r
2885 var operationParams = this.operation.parameters;
\r
2886 for (i = 0; i < operationParams.length; i++) {
\r
2887 var param = operationParams[i];
\r
2888 if (param.paramType === 'form')
\r
2889 values[param.name] = param;
\r
2892 if (headers['Content-Type'].indexOf('application/x-www-form-urlencoded') === 0) {
\r
2894 for (key in values) {
\r
2895 value = this.params[key];
\r
2896 if (typeof value !== 'undefined') {
\r
2897 if (encoded !== '')
\r
2899 encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
\r
2904 else if (headers['Content-Type'].indexOf('multipart/form-data') === 0) {
\r
2905 // encode the body for form submits
\r
2907 var boundary = '----SwaggerFormBoundary' + Date.now();
\r
2908 for (key in values) {
\r
2909 value = this.params[key];
\r
2910 if (typeof value !== 'undefined') {
\r
2911 data += '--' + boundary + '\n';
\r
2912 data += 'Content-Disposition: form-data; name="' + key + '"';
\r
2914 data += value + '\n';
\r
2917 data += '--' + boundary + '--\n';
\r
2918 headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
\r
2924 if (!((this.headers) && (this.headers.mock))) {
\r
2927 method: this.type,
\r
2930 useJQuery: this.useJQuery,
\r
2932 error: function (response) {
\r
2933 return _this.errorCallback(response, _this.opts.parent);
\r
2935 redirect: function (response) {
\r
2936 return _this.successCallback(response, _this.opts.parent);
\r
2938 307: function (response) {
\r
2939 return _this.successCallback(response, _this.opts.parent);
\r
2941 response: function (response) {
\r
2942 return _this.successCallback(response, _this.opts.parent);
\r
2947 var status = false;
\r
2948 if (this.operation.resource && this.operation.resource.api && this.operation.resource.api.clientAuthorizations) {
\r
2949 // Get the client authorizations from the resource declaration
\r
2950 status = this.operation.resource.api.clientAuthorizations.apply(obj, this.operation.authorizations);
\r
2952 // Get the client authorization from the default authorization declaration
\r
2954 if (typeof window !== 'undefined') {
\r
2959 status = e.authorizations.apply(obj, this.operation.authorizations);
\r
2963 if (status !== false) {
\r
2964 new SwaggerHttp().execute(obj);
\r
2966 obj.canceled = true;
\r
2975 SwaggerRequest.prototype.setHeaders = function (params, opts, operation) {
\r
2977 var accepts = opts.responseContentType || 'application/json';
\r
2978 var consumes = opts.requestContentType || 'application/json';
\r
2980 var allDefinedParams = operation.parameters;
\r
2981 var definedFormParams = [];
\r
2982 var definedFileParams = [];
\r
2983 var body = params.body;
\r
2986 // get params from the operation and set them in definedFileParams, definedFormParams, headers
\r
2988 for (i = 0; i < allDefinedParams.length; i++) {
\r
2989 var param = allDefinedParams[i];
\r
2990 if (param.paramType === 'form')
\r
2991 definedFormParams.push(param);
\r
2992 else if (param.paramType === 'file')
\r
2993 definedFileParams.push(param);
\r
2994 else if (param.paramType === 'header' && this.params.headers) {
\r
2995 var key = param.name;
\r
2996 var headerValue = this.params.headers[param.name];
\r
2997 if (typeof this.params.headers[param.name] !== 'undefined')
\r
2998 headers[key] = headerValue;
\r
3002 // if there's a body, need to set the accepts header via requestContentType
\r
3003 if (body && (this.type === 'POST' || this.type === 'PUT' || this.type === 'PATCH' || this.type === 'DELETE')) {
\r
3004 if (this.opts.requestContentType)
\r
3005 consumes = this.opts.requestContentType;
\r
3007 // if any form params, content type must be set
\r
3008 if (definedFormParams.length > 0) {
\r
3009 if (definedFileParams.length > 0)
\r
3010 consumes = 'multipart/form-data';
\r
3012 consumes = 'application/x-www-form-urlencoded';
\r
3014 else if (this.type === 'DELETE')
\r
3016 else if (this.type != 'DELETE')
\r
3020 if (consumes && this.operation.consumes) {
\r
3021 if (this.operation.consumes.indexOf(consumes) === -1) {
\r
3022 log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.operation.consumes));
\r
3026 if (this.opts && this.opts.responseContentType) {
\r
3027 accepts = this.opts.responseContentType;
\r
3029 accepts = 'application/json';
\r
3031 if (accepts && operation.produces) {
\r
3032 if (operation.produces.indexOf(accepts) === -1) {
\r
3033 log('server can\'t produce ' + accepts);
\r
3037 if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded'))
\r
3038 headers['Content-Type'] = consumes;
\r
3040 headers.Accept = accepts;
\r
3045 * SwaggerHttp is a wrapper for executing requests
\r
3047 var SwaggerHttp = function() {};
\r
3049 SwaggerHttp.prototype.execute = function(obj, opts) {
\r
3050 if(obj && (typeof obj.useJQuery === 'boolean'))
\r
3051 this.useJQuery = obj.useJQuery;
\r
3053 this.useJQuery = this.isIE8();
\r
3055 if(obj && typeof obj.body === 'object') {
\r
3056 if(obj.body.type && obj.body.type !== 'formData')
\r
3057 obj.body = JSON.stringify(obj.body);
\r
3059 obj.contentType = false;
\r
3060 obj.processData = false;
\r
3061 // delete obj.cache;
\r
3062 delete obj.headers['Content-Type'];
\r
3066 if(this.useJQuery)
\r
3067 return new JQueryHttpClient(opts).execute(obj);
\r
3069 return new ShredHttpClient(opts).execute(obj);
\r
3072 SwaggerHttp.prototype.isIE8 = function() {
\r
3073 var detectedIE = false;
\r
3074 if (typeof navigator !== 'undefined' && navigator.userAgent) {
\r
3075 nav = navigator.userAgent.toLowerCase();
\r
3076 if (nav.indexOf('msie') !== -1) {
\r
3077 var version = parseInt(nav.split('msie')[1]);
\r
3078 if (version <= 8) {
\r
3079 detectedIE = true;
\r
3083 return detectedIE;
\r
3087 * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic.
\r
3088 * NOTE: when jQuery is available it will export both '$' and 'jQuery' to the global space.
\r
3089 * Since we are using closures here we need to alias it for internal use.
\r
3091 var JQueryHttpClient = function(options) {
\r
3094 var jQuery = window.jQuery;
\r
3098 JQueryHttpClient.prototype.execute = function(obj) {
\r
3100 var request = obj;
\r
3102 obj.type = obj.method;
\r
3103 obj.cache = false;
\r
3104 delete obj.useJQuery;
\r
3107 obj.beforeSend = function(xhr) {
\r
3109 if (obj.headers) {
\r
3111 for (key in obj.headers) {
\r
3112 if (key.toLowerCase() === "content-type") {
\r
3113 results.push(obj.contentType = obj.headers[key]);
\r
3114 } else if (key.toLowerCase() === "accept") {
\r
3115 results.push(obj.accepts = obj.headers[key]);
\r
3117 results.push(xhr.setRequestHeader(key, obj.headers[key]));
\r
3124 obj.data = obj.body;
\r
3126 obj.complete = function(response, textStatus, opts) {
\r
3128 headerArray = response.getAllResponseHeaders().split("\n");
\r
3130 for(var i = 0; i < headerArray.length; i++) {
\r
3131 var toSplit = headerArray[i].trim();
\r
3132 if(toSplit.length === 0)
\r
3134 var separator = toSplit.indexOf(":");
\r
3135 if(separator === -1) {
\r
3136 // Name but no value in the header
\r
3137 headers[toSplit] = null;
\r
3140 var name = toSplit.substring(0, separator).trim(),
\r
3141 value = toSplit.substring(separator + 1).trim();
\r
3142 headers[name] = value;
\r
3147 method: request.method,
\r
3148 status: response.status,
\r
3149 statusText: response.statusText,
\r
3150 data: response.responseText,
\r
3154 var contentType = (headers["content-type"]||headers["Content-Type"]||null);
\r
3156 if(contentType.indexOf("application/json") === 0 || contentType.indexOf("+json") > 0) {
\r
3158 out.obj = response.responseJSON || JSON.parse(out.data) || {};
\r
3160 // do not set out.obj
\r
3161 log("unable to parse JSON content");
\r
3166 if(response.status >= 200 && response.status < 300)
\r
3168 else if(response.status === 0 || (response.status >= 400 && response.status < 599))
\r
3171 return cb.response(out);
\r
3174 jQuery.support.cors = true;
\r
3175 return jQuery.ajax(obj);
\r
3179 * ShredHttpClient is a light-weight, node or browser HTTP client
\r
3181 var ShredHttpClient = function(opts) {
\r
3182 this.opts = (opts||{});
\r
3183 this.isInitialized = false;
\r
3185 var identity, toString;
\r
3187 if (typeof window !== 'undefined') {
\r
3188 this.Shred = require("./shred");
\r
3189 this.content = require("./shred/content");
\r
3192 this.Shred = require("shred");
\r
3193 this.shred = new this.Shred(opts);
\r
3196 ShredHttpClient.prototype.initShred = function () {
\r
3197 this.isInitialized = true;
\r
3198 this.registerProcessors(this.shred);
\r
3201 ShredHttpClient.prototype.registerProcessors = function(shred) {
\r
3202 var identity = function(x) {
\r
3205 var toString = function(x) {
\r
3206 return x.toString();
\r
3209 if (typeof window !== 'undefined') {
\r
3210 this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
\r
3212 stringify: toString
\r
3215 this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
\r
3217 stringify: toString
\r
3222 ShredHttpClient.prototype.execute = function(obj) {
\r
3223 if(!this.isInitialized)
\r
3226 var cb = obj.on, res;
\r
3227 var transform = function(response) {
\r
3229 headers: response._headers,
\r
3230 url: response.request.url,
\r
3231 method: response.request.method,
\r
3232 status: response.status,
\r
3233 data: response.content.data
\r
3236 var headers = response._headers.normalized || response._headers;
\r
3237 var contentType = (headers["content-type"]||headers["Content-Type"]||null);
\r
3240 if(contentType.indexOf("application/json") === 0 || contentType.indexOf("+json") > 0) {
\r
3241 if(response.content.data && response.content.data !== "")
\r
3243 out.obj = JSON.parse(response.content.data);
\r
3246 // unable to parse
\r
3255 // Transform an error into a usable response-like object
\r
3256 var transformError = function (error) {
\r
3258 // Default to a status of 0 - The client will treat this as a generic permissions sort of error
\r
3260 data: error.message || error
\r
3266 if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
\r
3267 // We can tell the client that this should be treated as a missing resource and not as a permissions thing
\r
3275 error: function (response) {
\r
3277 return cb.error(transform(response));
\r
3279 // Catch the Shred error raised when the request errors as it is made (i.e. No Response is coming)
\r
3280 request_error: function (err) {
\r
3282 return cb.error(transformError(err));
\r
3284 response: function (response) {
\r
3286 return cb.response(transform(response));
\r
3293 return this.shred.request(obj);
\r
3297 var e = (typeof window !== 'undefined' ? window : exports);
\r
3299 e.authorizations = authorizations = new SwaggerAuthorizations();
\r
3300 e.ApiKeyAuthorization = ApiKeyAuthorization;
\r
3301 e.PasswordAuthorization = PasswordAuthorization;
\r
3302 e.CookieAuthorization = CookieAuthorization;
\r
3303 e.SwaggerClient = SwaggerClient;
\r
3304 e.SwaggerApi = SwaggerClient;
\r
3305 e.Operation = Operation;
\r
3307 e.addModel = addModel;
\r
3308 e.Resolver = Resolver;
\r