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