Make JavaScript client work in both Node.js and browser

* Replace jQuery with SuperAgent which works in both Node.js and browser
* Use UMD pattern (returnExports.js) to make the module exporting compatible
  with all major systems: AMD, Node.js (CommonJS) and browser
* Implement support of header and form parameters. Closes #1736
* Move HTTP requesting code to `ApiClient` and allow customizing options
  in it, e.g. "basePath"
* Update unit tests accordingly and add some tests for `ApiClient`
This commit is contained in:
xhh 2016-01-19 10:46:20 +08:00 committed by Maelig Nantel
parent a2cb3f7c3c
commit 6efbde5691
22 changed files with 3575 additions and 2106 deletions

View File

@ -134,6 +134,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
typeMapping.put("double", "Number"); typeMapping.put("double", "Number");
typeMapping.put("number", "Number"); typeMapping.put("number", "Number");
typeMapping.put("DateTime", "Date"); typeMapping.put("DateTime", "Date");
// binary not supported in JavaScript client right now, using Object as a workaround
typeMapping.put("binary", "Object");
importMapping.clear(); importMapping.clear();
} }
@ -206,6 +208,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js")); supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", sourceFolder, "ApiClient.js"));
} }
@Override @Override

View File

@ -0,0 +1,146 @@
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['superagent'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('superagent'));
} else {
// Browser globals (root is window)
if (!root.{{moduleName}}) {
root.{{moduleName}} = {};
}
root.{{moduleName}}.ApiClient = factory(root.superagent);
}
}(this, function(superagent) {
'use strict';
var ApiClient = function ApiClient() {
this.basePath = '{{basePath}}'.replace(/\/+$/, '');
};
ApiClient.prototype.paramToString = function paramToString(param) {
if (param == null) {
// return empty string for null and undefined
return '';
} else {
return param.toString();
}
};
/**
* Build full URL by appending the given path to base path and replacing
* path parameter placeholders with parameter values.
* NOTE: query parameters are not handled here.
*/
ApiClient.prototype.buildUrl = function buildUrl(path, pathParams) {
if (!path.match(/^\//)) {
path = '/' + path;
}
var url = this.basePath + path;
var _this = this;
url = url.replace(/\{([\w-]+)\}/g, function(fullMatch, key) {
var value;
if (pathParams.hasOwnProperty(key)) {
value = _this.paramToString(pathParams[key]);
} else {
value = fullMatch;
}
return encodeURIComponent(value);
});
return url;
};
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
*/
ApiClient.prototype.isJsonMime = function isJsonMime(mime) {
return Boolean(mime != null && mime.match(/^application\/json(;.*)?$/i));
};
/**
* Choose a MIME from the given MIMEs with JSON preferred,
* i.e. return JSON if included, otherwise return the first one.
*/
ApiClient.prototype.jsonPreferredMime = function jsonPreferredMime(mimes) {
var len = mimes.length;
for (var i = 0; i < len; i++) {
if (this.isJsonMime(mimes[i])) {
return mimes[i];
}
}
return mimes[0];
};
/**
* Normalize parameters values:
* remove nils,
* keep files and arrays,
* format to string with `paramToString` for other cases.
*/
ApiClient.prototype.normalizeParams = function normalizeParams(params) {
var newParams = {};
for (var key in params) {
if (params.hasOwnProperty(key) && params[key] != null) {
var value = params[key];
if (value instanceof Blob || Array.isArray(value)) {
newParams[key] = value;
} else {
newParams[key] = this.paramToString(value);
}
}
}
return newParams;
};
ApiClient.prototype.callApi = function callApi(path, httpMethod, pathParams,
queryParams, headerParams, formParams, bodyParam, contentTypes, accepts,
callback) {
var url = this.buildUrl(path, pathParams);
var request = superagent(httpMethod, url);
// set query parameters
request.query(this.normalizeParams(queryParams));
// set header parameters
request.set(this.normalizeParams(headerParams));
var contentType = this.jsonPreferredMime(contentTypes) || 'application/json';
request.type(contentType);
if (contentType === 'application/x-www-form-urlencoded') {
request.send(this.normalizeParams(formParams));
} else if (contentType == 'multipart/form-data') {
var _formParams = this.normalizeParams(formParams);
for (var key in _formParams) {
if (_formParams.hasOwnProperty(key)) {
if (_formParams[key] instanceof Blob) {
// file field
request.attach(key, _formParams[key]);
} else {
request.field(key, _formParams[key]);
}
}
}
} else if (bodyParam) {
request.send(bodyParam);
}
request.end(function(error, response) {
if (callback) {
var data = response && response.body;
callback(error, data, response);
}
});
return request;
};
ApiClient.default = new ApiClient();
return ApiClient;
}));

View File

@ -1,125 +1,86 @@
// require files in Node.js environment (function(root, factory) {
var ${{#imports}}, {{import}}{{/imports}}; if (typeof define === 'function' && define.amd) {
if (typeof module === 'object' && module.exports) { // AMD. Register as an anonymous module.
$ = require('jquery');{{#imports}} define(['../ApiClient'{{#imports}}, '../model/{{import}}'{{/imports}}], factory);
{{import}} = require('../model/{{import}}.js');{{/imports}} } else if (typeof module === 'object' && module.exports) {
} // CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient.js'){{#imports}}, require('../model/{{import}}.js'){{/imports}});
// export module for AMD } else {
if ( typeof define === "function" && define.amd ) { // Browser globals (root is window)
define(['jquery'{{#imports}}, '{{import}}'{{/imports}}], function(${{#imports}}, {{import}}{{/imports}}) { if (!root.{{moduleName}}) {
return {{classname}}; root.{{moduleName}} = {};
});
}
var {{classname}} = function {{classname}}() {
var self = this;
{{#operations}}
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}} * @param {{=<% %>=}}{<% dataType %>} <%={{ }}=%> {{paramName}} {{description}}
{{/allParams}} * @param {function} callback the callback function
* @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/
self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}callback) {
var {{localVariablePrefix}}postBody = {{#bodyParam}}{{^isBinary}}JSON.stringify({{paramName}}){{/isBinary}}{{#isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
var {{localVariablePrefix}}postBinaryBody = {{#bodyParam}}{{#isBinary}}{{paramName}}{{/isBinary}}{{^isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
//throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}");
var errorRequiredMsg = "Missing the required parameter '{{paramName}}' when calling {{nickname}}";
throw errorRequiredMsg;
}
{{/required}}{{/allParams}}
// create path and map variables
var basePath = '{{basePath}}';
// if basePath ends with a /, remove it as path starts with a leading /
if (basePath.substring(basePath.length-1, basePath.length)=='/') {
basePath = basePath.substring(0, basePath.length-1);
} }
root.{{moduleName}}.{{classname}} = factory(root.{{moduleName}}.ApiClient{{#imports}}, root.{{moduleName}}.{{import}}{{/imports}});
var {{localVariablePrefix}}path = basePath + replaceAll(replaceAll("{{{path}}}", "\\{format\\}","json"){{#pathParams}}
, "\\{" + "{{baseName}}" + "\\}", encodeURIComponent({{{paramName}}}.toString()){{/pathParams}});
var queryParams = {};
var headerParams = {};
var formParams = {};
{{#queryParams}}
queryParams.{{baseName}} = {{paramName}};
{{/queryParams}}
{{#headerParams}}if ({{paramName}} != null)
{{localVariablePrefix}}headerParams.put("{{baseName}}", {{paramName}});
{{/headerParams}}
{{#formParams}}if ({{paramName}} != null)
{{localVariablePrefix}}formParams.put("{{baseName}}", {{paramName}});
{{/formParams}}
path += createQueryString(queryParams);
var options = {type: "{{httpMethod}}", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
{{#returnType}}
/**
* @returns {{{returnType}}}
*/
{{#returnTypeIsPrimitive}}var myResponse = response;{{/returnTypeIsPrimitive}}
{{^returnTypeIsPrimitive}}var myResponse = new {{{returnType}}}();
myResponse.constructFromObject(response);{{/returnTypeIsPrimitive}}
if (callback) {
callback(myResponse, textStatus, jqXHR);
}
{{/returnType}}{{^returnType}}
if (callback) {
callback(response, textStatus, jqXHR);
}
{{/returnType}}
});
return request;
} }
{{/operation}} }(this, function(ApiClient{{#imports}}, {{import}}{{/imports}}) {
{{/operations}} 'use strict';
function replaceAll (haystack, needle, replace) { var {{classname}} = function {{classname}}(apiClient) {
var result= haystack; this.apiClient = apiClient || ApiClient.default;
if (needle !=null && replace!=null) {
result= haystack.replace(new RegExp(needle, 'g'), replace);
}
return result;
}
function createQueryString (queryParams) { var self = this;
var queryString =''; {{#operations}}
var i = 0; {{#operation}}
for (var queryParamName in queryParams) { /**
if (i==0) { * {{summary}}
queryString += '?' ; * {{notes}}
} else { {{#allParams}} * @param {{=<% %>=}}{<% dataType %>} <%={{ }}=%> {{paramName}} {{description}}
queryString += '&' ; {{/allParams}} * @param {function} callback the callback function, accepting three arguments: error, data, response{{#returnType}}
} * data is of type: {{{returnType}}}{{/returnType}}
*/
queryString += queryParamName + '=' + encodeURIComponent(queryParams[queryParamName]); self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}callback) {
i++; var postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
} {{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
return queryString; if ({{paramName}} == null) {
} throw "Missing the required parameter '{{paramName}}' when calling {{nickname}}";
} }
{{/required}}{{/allParams}}
// export module for Node.js {{=< >=}}
if (typeof module === 'object' && module.exports) { var pathParams = {<#pathParams>
module.exports = {{classname}}; '<baseName>': <paramName><#hasMore>,</hasMore></pathParams>
} };
var queryParams = {<#queryParams>
'<baseName>': <paramName><#hasMore>,</hasMore></queryParams>
};
var headerParams = {<#headerParams>
'<baseName>': <paramName><#hasMore>,</hasMore></headerParams>
};
var formParams = {<#formParams>
'<baseName>': <paramName><#hasMore>,</hasMore></formParams>
};
var contentTypes = [<#consumes>'<mediaType>'<#hasMore>, </hasMore></consumes>];
var accepts = [<#produces>'<mediaType>'<#hasMore>, </hasMore></produces>];
var handleResponse = null;
if (callback) {
handleResponse = function(error, data, response) {<#returnType><#returnTypeIsPrimitive>
callback(error, data, response);</returnTypeIsPrimitive><^returnTypeIsPrimitive><#isListContainer>
// TODO: support deserializing array of models
callback(error, data, response);</isListContainer><^isListContainer>
if (!error && data) {
var result = new <&returnType>();
result.constructFromObject(data);
callback(error, result, response);
} else {
callback(error, data, response);
}</isListContainer></returnTypeIsPrimitive></returnType><^returnType>
callback(error, data, response);</returnType>
};
}
return this.apiClient.callApi(
'<&path>', '<httpMethod>',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
<={{ }}=>
}
{{/operation}}
{{/operations}}
};
return {{classname}};
}));

View File

@ -1,10 +1,17 @@
if (typeof module === 'object' && module.exports) { (function(factory) {
var {{moduleName}} = {}; if (typeof define === 'function' && define.amd) {
{{#models}} // AMD. Register as an anonymous module.
{{moduleName}}.{{importPath}} = require('./model/{{importPath}}.js'); define(['./ApiClient'{{#models}}, './model/{{importPath}}'{{/models}}{{#apiInfo}}{{#apis}}, './api/{{importPath}}'{{/apis}}{{/apiInfo}}], factory);
{{/models}} } else if (typeof module === 'object' && module.exports) {
{{#apiInfo}}{{#apis}} // CommonJS-like environments that support module.exports, like Node.
{{moduleName}}.{{importPath}} = require('./api/{{importPath}}.js'); module.exports = factory(require('./ApiClient.js'){{#models}}, require('./model/{{importPath}}.js'){{/models}}{{#apiInfo}}{{#apis}}, require('./api/{{importPath}}.js'){{/apis}}{{/apiInfo}});
{{/apis}}{{/apiInfo}} }
module.exports = {{moduleName}}; }(function(ApiClient{{#models}}, {{importPath}}{{/models}}{{#apiInfo}}{{#apis}}, {{importPath}}{{/apis}}{{/apiInfo}}) {
} 'use strict';
return {
ApiClient: ApiClient{{#models}},
{{importPath}}: {{importPath}}{{/models}}{{#apiInfo}}{{#apis}},
{{importPath}}: {{importPath}}{{/apis}}{{/apiInfo}}
};
}));

View File

@ -1,75 +1,79 @@
// require files in Node.js environment (function(root, factory) {
{{#imports}} if (typeof define === 'function' && define.amd) {
var {{import}};{{/imports}} // AMD. Register as an anonymous module.
if (typeof module === 'object' && module.exports) { define([undefined{{#imports}}, './{{import}}'{{/imports}}], factory);
{{#imports}} } else if (typeof module === 'object' && module.exports) {
{{import}} = require('./{{import}}.js');{{/imports}} // CommonJS-like environments that support module.exports, like Node.
} module.exports = factory(undefined{{#imports}}, require('./{{import}}.js'){{/imports}});
} else {
{{#models}}{{#model}} // Browser globals (root is window)
{{#vars}}{{#isEnum}}{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} if (!root.{{moduleName}}) {
{{>enumClass}}{{/items}}*/{{/items.isEnum}}{{/vars}} root.{{moduleName}} = {};
//export module
if ( typeof define === "function" && define.amd ) {
define('{{classname}}', ['jquery'{{#vars}}{{^isPrimitiveType}}{{^-last}}, {{/-last}}'{{datatypeWithEnum}}'{{/isPrimitiveType}}{{/vars}}],
function(${{#vars}}{{^isPrimitiveType}}{{^-last}}, {{/-last}}{{datatypeWithEnum}}{{/isPrimitiveType}}{{/vars}}) {
return {{classname}};
});
}
{{#description}}/**
* {{description}}
**/{{/description}}
var {{classname}} = function {{classname}}({{#mandatory}}{{this}}{{^-last}}, {{/-last}}{{/mandatory}}) { {{#parent}}/* extends {{{parent}}}*/{{/parent}}
var self = this;
{{#vars}}
/**{{#description}}
* {{{description}}}{{/description}}
* datatype: {{{datatypeWithEnum}}}{{#required}}
* required{{/required}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
**/
self.{{name}} = {{#required}}{{name}}{{/required}}{{^required}}{{{defaultValue}}}{{/required}};
{{/vars}}
self.constructFromObject = function(data) {
if (!data) {
return;
} }
factory(root.{{moduleName}}{{#imports}}, root.{{moduleName}}.{{import}}{{/imports}});
}
}(this, function(module{{#imports}}, {{import}}{{/imports}}) {
'use strict';
{{#models}}{{#model}}
{{#vars}}{{#isEnum}}{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}}
{{>enumClass}}{{/items}}*/{{/items.isEnum}}{{/vars}}
{{#description}}/**
* {{description}}
**/{{/description}}
var {{classname}} = function {{classname}}({{#mandatory}}{{this}}{{^-last}}, {{/-last}}{{/mandatory}}) { {{#parent}}/* extends {{{parent}}}*/{{/parent}}
var self = this;
{{#vars}} {{#vars}}
self.{{name}}{{{defaultValueWithParam}}} /**{{#description}}
* {{{description}}}{{/description}}
* datatype: {{{datatypeWithEnum}}}{{#required}}
* required{{/required}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
**/
self.{{name}} = {{#required}}{{name}}{{/required}}{{^required}}{{{defaultValue}}}{{/required}};
{{/vars}} {{/vars}}
self.constructFromObject = function(data) {
if (!data) {
return;
}
{{#vars}}
self.{{name}}{{{defaultValueWithParam}}}
{{/vars}}
}
{{#vars}}
/**{{#description}}
* get {{{description}}}{{/description}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
* @return {{=<% %>=}}{<% datatypeWithEnum %>}<%={{ }}=%>
**/
self.{{getter}} = function() {
return self.{{name}};
}
/**{{#description}}
* set {{{description}}}{{/description}}
* @param {{=<% %>=}}{<% datatypeWithEnum %>}<%={{ }}=%> {{name}}
**/
self.{{setter}} = function ({{name}}) {
self.{{name}} = {{name}};
}
{{/vars}}
self.toJson = function () {
return JSON.stringify(self);
}
};
if (module) {
module.{{classname}} = {{classname}};
} }
{{#vars}} return {{classname}};
/**{{#description}} {{/model}}
* get {{{description}}}{{/description}}{{#minimum}} {{/models}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}} }));
* maximum: {{maximum}}{{/maximum}}
* @return {{=<% %>=}}{<% datatypeWithEnum %>}<%={{ }}=%>
**/
self.{{getter}} = function() {
return self.{{name}};
}
/**{{#description}}
* set {{{description}}}{{/description}}
* @param {{=<% %>=}}{<% datatypeWithEnum %>}<%={{ }}=%> {{name}}
**/
self.{{setter}} = function ({{name}}) {
self.{{name}} = {{name}};
}
{{/vars}}
self.toJson = function () {
return JSON.stringify(self);
}
}
if (typeof module === 'object' && module.exports) {
module.exports = {{classname}};
}
{{/model}}
{{/models}}

View File

@ -8,13 +8,10 @@
"test": "./node_modules/mocha/bin/mocha --recursive" "test": "./node_modules/mocha/bin/mocha --recursive"
}, },
"dependencies": { "dependencies": {
"jquery": "~2.1.4" "superagent": "^1.6.1"
}, },
"devDependencies": { "devDependencies": {
"mocha": "~2.3.4", "mocha": "~2.3.4",
"expect.js": "~0.3.1", "expect.js": "~0.3.1"
"mockrequire": "~0.0.5",
"domino": "~1.0.20",
"xmlhttprequest": "~1.8.0"
} }
} }

View File

@ -8,13 +8,10 @@
"test": "./node_modules/mocha/bin/mocha --recursive" "test": "./node_modules/mocha/bin/mocha --recursive"
}, },
"dependencies": { "dependencies": {
"jquery": "~2.1.4" "superagent": "^1.6.1"
}, },
"devDependencies": { "devDependencies": {
"mocha": "~2.3.4", "mocha": "~2.3.4",
"expect.js": "~0.3.1", "expect.js": "~0.3.1"
"mockrequire": "~0.0.5",
"domino": "~1.0.20",
"xmlhttprequest": "~1.8.0"
} }
} }

View File

@ -0,0 +1,146 @@
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['superagent'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('superagent'));
} else {
// Browser globals (root is window)
if (!root.SwaggerPetstore) {
root.SwaggerPetstore = {};
}
root.SwaggerPetstore.ApiClient = factory(root.superagent);
}
}(this, function(superagent) {
'use strict';
var ApiClient = function ApiClient() {
this.basePath = 'http://petstore.swagger.io/v2'.replace(/\/+$/, '');
};
ApiClient.prototype.paramToString = function paramToString(param) {
if (param == null) {
// return empty string for null and undefined
return '';
} else {
return param.toString();
}
};
/**
* Build full URL by appending the given path to base path and replacing
* path parameter placeholders with parameter values.
* NOTE: query parameters are not handled here.
*/
ApiClient.prototype.buildUrl = function buildUrl(path, pathParams) {
if (!path.match(/^\//)) {
path = '/' + path;
}
var url = this.basePath + path;
var _this = this;
url = url.replace(/\{([\w-]+)\}/g, function(fullMatch, key) {
var value;
if (pathParams.hasOwnProperty(key)) {
value = _this.paramToString(pathParams[key]);
} else {
value = fullMatch;
}
return encodeURIComponent(value);
});
return url;
};
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
*/
ApiClient.prototype.isJsonMime = function isJsonMime(mime) {
return Boolean(mime != null && mime.match(/^application\/json(;.*)?$/i));
};
/**
* Choose a MIME from the given MIMEs with JSON preferred,
* i.e. return JSON if included, otherwise return the first one.
*/
ApiClient.prototype.jsonPreferredMime = function jsonPreferredMime(mimes) {
var len = mimes.length;
for (var i = 0; i < len; i++) {
if (this.isJsonMime(mimes[i])) {
return mimes[i];
}
}
return mimes[0];
};
/**
* Normalize parameters values:
* remove nils,
* keep files and arrays,
* format to string with `paramToString` for other cases.
*/
ApiClient.prototype.normalizeParams = function normalizeParams(params) {
var newParams = {};
for (var key in params) {
if (params.hasOwnProperty(key) && params[key] != null) {
var value = params[key];
if (value instanceof Blob || Array.isArray(value)) {
newParams[key] = value;
} else {
newParams[key] = this.paramToString(value);
}
}
}
return newParams;
};
ApiClient.prototype.callApi = function callApi(path, httpMethod, pathParams,
queryParams, headerParams, formParams, bodyParam, contentTypes, accepts,
callback) {
var url = this.buildUrl(path, pathParams);
var request = superagent(httpMethod, url);
// set query parameters
request.query(this.normalizeParams(queryParams));
// set header parameters
request.set(this.normalizeParams(headerParams));
var contentType = this.jsonPreferredMime(contentTypes) || 'application/json';
request.type(contentType);
if (contentType === 'application/x-www-form-urlencoded') {
request.send(this.normalizeParams(formParams));
} else if (contentType == 'multipart/form-data') {
var _formParams = this.normalizeParams(formParams);
for (var key in _formParams) {
if (_formParams.hasOwnProperty(key)) {
if (_formParams[key] instanceof Blob) {
// file field
request.attach(key, _formParams[key]);
} else {
request.field(key, _formParams[key]);
}
}
}
} else if (bodyParam) {
request.send(bodyParam);
}
request.end(function(error, response) {
if (callback) {
var data = response && response.body;
callback(error, data, response);
}
});
return request;
};
ApiClient.default = new ApiClient();
return ApiClient;
}));

View File

@ -1,527 +1,462 @@
// require files in Node.js environment (function(root, factory) {
var $, Pet; if (typeof define === 'function' && define.amd) {
if (typeof module === 'object' && module.exports) { // AMD. Register as an anonymous module.
$ = require('jquery'); define(['../ApiClient', '../model/Pet'], factory);
Pet = require('../model/Pet.js'); } else if (typeof module === 'object' && module.exports) {
} // CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient.js'), require('../model/Pet.js'));
} else {
// Browser globals (root is window)
if (!root.SwaggerPetstore) {
root.SwaggerPetstore = {};
}
root.SwaggerPetstore.PetApi = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Pet);
}
}(this, function(ApiClient, Pet) {
'use strict';
// export module for AMD var PetApi = function PetApi(apiClient) {
if ( typeof define === "function" && define.amd ) { this.apiClient = apiClient || ApiClient.default;
define(['jquery', 'Pet'], function($, Pet) {
return PetApi;
});
}
var PetApi = function PetApi() { var self = this;
var self = this;
/**
* Update an existing pet
*
* @param {Pet} body Pet object that needs to be added to the store
* @param {function} callback the callback function
* @return void
*/
self.updatePet = function(body, callback) {
var postBody = JSON.stringify(body);
var postBinaryBody = null;
// create path and map variables
var basePath = 'http://petstore.swagger.io/v2'; /**
// if basePath ends with a /, remove it as path starts with a leading / * Update an existing pet
if (basePath.substring(basePath.length-1, basePath.length)=='/') { *
basePath = basePath.substring(0, basePath.length-1); * @param {Pet} body Pet object that needs to be added to the store
* @param {function} callback the callback function, accepting three arguments: error, data, response
*/
self.updatePet = function(body, callback) {
var postBody = body;
var pathParams = {
};
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var contentTypes = ['application/json', 'application/xml'];
var accepts = ['application/json', 'application/xml'];
var handleResponse = null;
if (callback) {
handleResponse = function(error, data, response) {
callback(error, data, response);
};
}
return this.apiClient.callApi(
'/pet', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
} }
var path = basePath + replaceAll(replaceAll("/pet", "\\{format\\}","json")); /**
* Add a new pet to the store
var queryParams = {}; *
var headerParams = {}; * @param {Pet} body Pet object that needs to be added to the store
var formParams = {}; * @param {function} callback the callback function, accepting three arguments: error, data, response
*/
self.addPet = function(body, callback) {
var postBody = body;
path += createQueryString(queryParams);
var options = {type: "PUT", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
if (callback) {
callback(response, textStatus, jqXHR);
} var pathParams = {
};
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var contentTypes = ['application/json', 'application/xml'];
var accepts = ['application/json', 'application/xml'];
var handleResponse = null;
if (callback) {
handleResponse = function(error, data, response) {
callback(error, data, response);
};
}
return this.apiClient.callApi(
'/pet', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
});
return request;
}
/**
* Add a new pet to the store
*
* @param {Pet} body Pet object that needs to be added to the store
* @param {function} callback the callback function
* @return void
*/
self.addPet = function(body, callback) {
var postBody = JSON.stringify(body);
var postBinaryBody = null;
// create path and map variables
var basePath = 'http://petstore.swagger.io/v2';
// if basePath ends with a /, remove it as path starts with a leading /
if (basePath.substring(basePath.length-1, basePath.length)=='/') {
basePath = basePath.substring(0, basePath.length-1);
} }
var path = basePath + replaceAll(replaceAll("/pet", "\\{format\\}","json")); /**
* Finds Pets by status
var queryParams = {}; * Multiple status values can be provided with comma seperated strings
var headerParams = {}; * @param {Array} status Status values that need to be considered for filter
var formParams = {}; * @param {function} callback the callback function, accepting three arguments: error, data, response
* data is of type: Array
*/
self.findPetsByStatus = function(status, callback) {
var postBody = null;
path += createQueryString(queryParams);
var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
if (callback) {
callback(response, textStatus, jqXHR);
} var pathParams = {
};
var queryParams = {
'status': status
};
var headerParams = {
};
var formParams = {
};
var contentTypes = [];
var accepts = ['application/json', 'application/xml'];
var handleResponse = null;
if (callback) {
handleResponse = function(error, data, response) {
// TODO: support deserializing array of models
callback(error, data, response);
};
}
return this.apiClient.callApi(
'/pet/findByStatus', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
});
return request;
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma seperated strings
* @param {Array} status Status values that need to be considered for filter
* @param {function} callback the callback function
* @return Array
*/
self.findPetsByStatus = function(status, callback) {
var postBody = null;
var postBinaryBody = null;
// create path and map variables
var basePath = 'http://petstore.swagger.io/v2';
// if basePath ends with a /, remove it as path starts with a leading /
if (basePath.substring(basePath.length-1, basePath.length)=='/') {
basePath = basePath.substring(0, basePath.length-1);
} }
var path = basePath + replaceAll(replaceAll("/pet/findByStatus", "\\{format\\}","json")); /**
* Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* @param {Array} tags Tags to filter by
* @param {function} callback the callback function, accepting three arguments: error, data, response
* data is of type: Array
*/
self.findPetsByTags = function(tags, callback) {
var postBody = null;
var queryParams = {};
var headerParams = {}; var pathParams = {
var formParams = {}; };
var queryParams = {
'tags': tags
};
var headerParams = {
};
var formParams = {
};
var contentTypes = [];
queryParams.status = status; var accepts = ['application/json', 'application/xml'];
path += createQueryString(queryParams); var handleResponse = null;
var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) { if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error'; handleResponse = function(error, data, response) {
callback(null, textStatus, jqXHR, error); // TODO: support deserializing array of models
callback(error, data, response);
};
} }
});
return this.apiClient.callApi(
request.done(function(response, textStatus, jqXHR){ '/pet/findByTags', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
/**
* @returns Array
*/
var myResponse = new Array();
myResponse.constructFromObject(response);
if (callback) {
callback(myResponse, textStatus, jqXHR);
}
});
return request;
}
/**
* Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* @param {Array} tags Tags to filter by
* @param {function} callback the callback function
* @return Array
*/
self.findPetsByTags = function(tags, callback) {
var postBody = null;
var postBinaryBody = null;
// create path and map variables
var basePath = 'http://petstore.swagger.io/v2';
// if basePath ends with a /, remove it as path starts with a leading /
if (basePath.substring(basePath.length-1, basePath.length)=='/') {
basePath = basePath.substring(0, basePath.length-1);
} }
var path = basePath + replaceAll(replaceAll("/pet/findByTags", "\\{format\\}","json")); /**
* Find pet by ID
var queryParams = {}; * Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
var headerParams = {}; * @param {Integer} petId ID of pet that needs to be fetched
var formParams = {}; * @param {function} callback the callback function, accepting three arguments: error, data, response
* data is of type: Pet
*/
queryParams.tags = tags; self.getPetById = function(petId, callback) {
var postBody = null;
path += createQueryString(queryParams);
var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
/** // verify the required parameter 'petId' is set
* @returns Array if (petId == null) {
*/ throw "Missing the required parameter 'petId' when calling getPetById";
var myResponse = new Array();
myResponse.constructFromObject(response);
if (callback) {
callback(myResponse, textStatus, jqXHR);
} }
});
return request; var pathParams = {
} 'petId': petId
};
/** var queryParams = {
* Find pet by ID };
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions var headerParams = {
* @param {Integer} petId ID of pet that needs to be fetched };
* @param {function} callback the callback function var formParams = {
* @return Pet };
*/
self.getPetById = function(petId, callback) { var contentTypes = [];
var postBody = null; var accepts = ['application/json', 'application/xml'];
var postBinaryBody = null;
var handleResponse = null;
// verify the required parameter 'petId' is set if (callback) {
if (petId == null) { handleResponse = function(error, data, response) {
//throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); if (!error && data) {
var errorRequiredMsg = "Missing the required parameter 'petId' when calling getPetById"; var result = new Pet();
throw errorRequiredMsg; result.constructFromObject(data);
} callback(error, result, response);
} else {
// create path and map variables callback(error, data, response);
var basePath = 'http://petstore.swagger.io/v2'; }
// if basePath ends with a /, remove it as path starts with a leading / };
if (basePath.substring(basePath.length-1, basePath.length)=='/') { }
basePath = basePath.substring(0, basePath.length-1);
return this.apiClient.callApi(
'/pet/{petId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
} }
var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") /**
, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); * Updates a pet in the store with form data
*
var queryParams = {}; * @param {String} petId ID of pet that needs to be updated
var headerParams = {}; * @param {String} name Updated name of the pet
var formParams = {}; * @param {String} status Updated status of the pet
* @param {function} callback the callback function, accepting three arguments: error, data, response
*/
self.updatePetWithForm = function(petId, name, status, callback) {
var postBody = null;
path += createQueryString(queryParams);
var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
/** // verify the required parameter 'petId' is set
* @returns Pet if (petId == null) {
*/ throw "Missing the required parameter 'petId' when calling updatePetWithForm";
var myResponse = new Pet();
myResponse.constructFromObject(response);
if (callback) {
callback(myResponse, textStatus, jqXHR);
} }
});
return request; var pathParams = {
} 'petId': petId
};
/** var queryParams = {
* Updates a pet in the store with form data };
* var headerParams = {
* @param {String} petId ID of pet that needs to be updated };
* @param {String} name Updated name of the pet var formParams = {
* @param {String} status Updated status of the pet 'name': name,
* @param {function} callback the callback function 'status': status
* @return void };
*/
self.updatePetWithForm = function(petId, name, status, callback) { var contentTypes = ['application/x-www-form-urlencoded'];
var postBody = null; var accepts = ['application/json', 'application/xml'];
var postBinaryBody = null;
var handleResponse = null;
// verify the required parameter 'petId' is set if (callback) {
if (petId == null) { handleResponse = function(error, data, response) {
//throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); callback(error, data, response);
var errorRequiredMsg = "Missing the required parameter 'petId' when calling updatePetWithForm"; };
throw errorRequiredMsg; }
}
return this.apiClient.callApi(
// create path and map variables '/pet/{petId}', 'POST',
var basePath = 'http://petstore.swagger.io/v2'; pathParams, queryParams, headerParams, formParams, postBody,
// if basePath ends with a /, remove it as path starts with a leading / contentTypes, accepts, handleResponse
if (basePath.substring(basePath.length-1, basePath.length)=='/') { );
basePath = basePath.substring(0, basePath.length-1);
} }
var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") /**
, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); * Deletes a pet
*
var queryParams = {}; * @param {Integer} petId Pet id to delete
var headerParams = {}; * @param {String} apiKey
var formParams = {}; * @param {function} callback the callback function, accepting three arguments: error, data, response
*/
self.deletePet = function(petId, apiKey, callback) {
var postBody = null;
if (name != null)
formParams.put("name", name);
if (status != null)
formParams.put("status", status);
path += createQueryString(queryParams);
var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
if (callback) { // verify the required parameter 'petId' is set
callback(response, textStatus, jqXHR); if (petId == null) {
throw "Missing the required parameter 'petId' when calling deletePet";
} }
});
return request; var pathParams = {
} 'petId': petId
};
/** var queryParams = {
* Deletes a pet };
* var headerParams = {
* @param {Integer} petId Pet id to delete 'api_key': apiKey
* @param {String} apiKey };
* @param {function} callback the callback function var formParams = {
* @return void };
*/
self.deletePet = function(petId, apiKey, callback) { var contentTypes = [];
var postBody = null; var accepts = ['application/json', 'application/xml'];
var postBinaryBody = null;
var handleResponse = null;
// verify the required parameter 'petId' is set if (callback) {
if (petId == null) { handleResponse = function(error, data, response) {
//throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); callback(error, data, response);
var errorRequiredMsg = "Missing the required parameter 'petId' when calling deletePet"; };
throw errorRequiredMsg; }
}
return this.apiClient.callApi(
// create path and map variables '/pet/{petId}', 'DELETE',
var basePath = 'http://petstore.swagger.io/v2'; pathParams, queryParams, headerParams, formParams, postBody,
// if basePath ends with a /, remove it as path starts with a leading / contentTypes, accepts, handleResponse
if (basePath.substring(basePath.length-1, basePath.length)=='/') { );
basePath = basePath.substring(0, basePath.length-1);
} }
var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") /**
, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); * uploads an image
*
var queryParams = {}; * @param {Integer} petId ID of pet to update
var headerParams = {}; * @param {String} additionalMetadata Additional data to pass to server
var formParams = {}; * @param {File} file file to upload
* @param {function} callback the callback function, accepting three arguments: error, data, response
*/
if (apiKey != null) self.uploadFile = function(petId, additionalMetadata, file, callback) {
headerParams.put("api_key", apiKey); var postBody = null;
path += createQueryString(queryParams);
var options = {type: "DELETE", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
if (callback) { // verify the required parameter 'petId' is set
callback(response, textStatus, jqXHR); if (petId == null) {
throw "Missing the required parameter 'petId' when calling uploadFile";
} }
});
return request; var pathParams = {
} 'petId': petId
};
/** var queryParams = {
* uploads an image };
* var headerParams = {
* @param {Integer} petId ID of pet to update };
* @param {String} additionalMetadata Additional data to pass to server var formParams = {
* @param {File} file file to upload 'additionalMetadata': additionalMetadata,
* @param {function} callback the callback function 'file': file
* @return void };
*/
self.uploadFile = function(petId, additionalMetadata, file, callback) { var contentTypes = ['multipart/form-data'];
var postBody = null; var accepts = ['application/json', 'application/xml'];
var postBinaryBody = null;
var handleResponse = null;
// verify the required parameter 'petId' is set if (callback) {
if (petId == null) { handleResponse = function(error, data, response) {
//throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); callback(error, data, response);
var errorRequiredMsg = "Missing the required parameter 'petId' when calling uploadFile"; };
throw errorRequiredMsg; }
}
return this.apiClient.callApi(
// create path and map variables '/pet/{petId}/uploadImage', 'POST',
var basePath = 'http://petstore.swagger.io/v2'; pathParams, queryParams, headerParams, formParams, postBody,
// if basePath ends with a /, remove it as path starts with a leading / contentTypes, accepts, handleResponse
if (basePath.substring(basePath.length-1, basePath.length)=='/') { );
basePath = basePath.substring(0, basePath.length-1);
} }
var path = basePath + replaceAll(replaceAll("/pet/{petId}/uploadImage", "\\{format\\}","json") /**
, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); * Fake endpoint to test byte array return by &#39;Find pet by ID&#39;
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
var queryParams = {}; * @param {Integer} petId ID of pet that needs to be fetched
var headerParams = {}; * @param {function} callback the callback function, accepting three arguments: error, data, response
var formParams = {}; * data is of type: Object
*/
self.getPetByIdWithByteArray = function(petId, callback) {
var postBody = null;
if (additionalMetadata != null)
formParams.put("additionalMetadata", additionalMetadata);
if (file != null)
formParams.put("file", file);
path += createQueryString(queryParams);
var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
if (callback) { // verify the required parameter 'petId' is set
callback(response, textStatus, jqXHR); if (petId == null) {
throw "Missing the required parameter 'petId' when calling getPetByIdWithByteArray";
} }
});
return request;
}
function replaceAll (haystack, needle, replace) {
var result= haystack; var pathParams = {
if (needle !=null && replace!=null) { 'petId': petId
result= haystack.replace(new RegExp(needle, 'g'), replace); };
} var queryParams = {
return result; };
} var headerParams = {
};
var formParams = {
};
function createQueryString (queryParams) { var contentTypes = [];
var queryString =''; var accepts = ['application/json', 'application/xml'];
var i = 0;
for (var queryParamName in queryParams) {
if (i==0) {
queryString += '?' ;
} else {
queryString += '&' ;
}
queryString += queryParamName + '=' + encodeURIComponent(queryParams[queryParamName]);
i++;
}
return queryString;
}
}
// export module for Node.js var handleResponse = null;
if (typeof module === 'object' && module.exports) { if (callback) {
module.exports = PetApi; handleResponse = function(error, data, response) {
} callback(error, data, response);
};
}
return this.apiClient.callApi(
'/pet/{petId}?testing_byte_array=true', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
}
/**
* Fake endpoint to test byte array in body parameter for adding a new pet to the store
*
* @param {Object} body Pet object in the form of byte array
* @param {function} callback the callback function, accepting three arguments: error, data, response
*/
self.addPetUsingByteArray = function(body, callback) {
var postBody = body;
var pathParams = {
};
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var contentTypes = ['application/json', 'application/xml'];
var accepts = ['application/json', 'application/xml'];
var handleResponse = null;
if (callback) {
handleResponse = function(error, data, response) {
callback(error, data, response);
};
}
return this.apiClient.callApi(
'/pet?testing_byte_array=true', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
}
};
return PetApi;
}));

View File

@ -1,286 +1,206 @@
// require files in Node.js environment (function(root, factory) {
var $, Order; if (typeof define === 'function' && define.amd) {
if (typeof module === 'object' && module.exports) { // AMD. Register as an anonymous module.
$ = require('jquery'); define(['../ApiClient', '../model/Order'], factory);
Order = require('../model/Order.js'); } else if (typeof module === 'object' && module.exports) {
} // CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient.js'), require('../model/Order.js'));
} else {
// Browser globals (root is window)
if (!root.SwaggerPetstore) {
root.SwaggerPetstore = {};
}
root.SwaggerPetstore.StoreApi = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Order);
}
}(this, function(ApiClient, Order) {
'use strict';
// export module for AMD var StoreApi = function StoreApi(apiClient) {
if ( typeof define === "function" && define.amd ) { this.apiClient = apiClient || ApiClient.default;
define(['jquery', 'Order'], function($, Order) {
return StoreApi;
});
}
var StoreApi = function StoreApi() { var self = this;
var self = this;
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @param {function} callback the callback function
* @return Object<String, Integer>
*/
self.getInventory = function(callback) {
var postBody = null;
var postBinaryBody = null;
// create path and map variables
var basePath = 'http://petstore.swagger.io/v2'; /**
// if basePath ends with a /, remove it as path starts with a leading / * Returns pet inventories by status
if (basePath.substring(basePath.length-1, basePath.length)=='/') { * Returns a map of status codes to quantities
basePath = basePath.substring(0, basePath.length-1); * @param {function} callback the callback function, accepting three arguments: error, data, response
* data is of type: Object<String, Integer>
*/
self.getInventory = function(callback) {
var postBody = null;
var pathParams = {
};
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var contentTypes = [];
var accepts = ['application/json', 'application/xml'];
var handleResponse = null;
if (callback) {
handleResponse = function(error, data, response) {
callback(error, data, response);
};
}
return this.apiClient.callApi(
'/store/inventory', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
} }
var path = basePath + replaceAll(replaceAll("/store/inventory", "\\{format\\}","json")); /**
* Place an order for a pet
*
* @param {Order} body order placed for purchasing the pet
* @param {function} callback the callback function, accepting three arguments: error, data, response
* data is of type: Order
*/
self.placeOrder = function(body, callback) {
var postBody = body;
var queryParams = {};
var headerParams = {}; var pathParams = {
var formParams = {}; };
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var contentTypes = [];
var accepts = ['application/json', 'application/xml'];
path += createQueryString(queryParams); var handleResponse = null;
var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) { if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error'; handleResponse = function(error, data, response) {
callback(null, textStatus, jqXHR, error); if (!error && data) {
var result = new Order();
result.constructFromObject(data);
callback(error, result, response);
} else {
callback(error, data, response);
}
};
} }
});
return this.apiClient.callApi(
request.done(function(response, textStatus, jqXHR){ '/store/order', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
/**
* @returns Object<String, Integer>
*/
var myResponse = response;
if (callback) {
callback(myResponse, textStatus, jqXHR);
}
});
return request;
}
/**
* Place an order for a pet
*
* @param {Order} body order placed for purchasing the pet
* @param {function} callback the callback function
* @return Order
*/
self.placeOrder = function(body, callback) {
var postBody = JSON.stringify(body);
var postBinaryBody = null;
// create path and map variables
var basePath = 'http://petstore.swagger.io/v2';
// if basePath ends with a /, remove it as path starts with a leading /
if (basePath.substring(basePath.length-1, basePath.length)=='/') {
basePath = basePath.substring(0, basePath.length-1);
} }
var path = basePath + replaceAll(replaceAll("/store/order", "\\{format\\}","json")); /**
* Find purchase order by ID
var queryParams = {}; * For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
var headerParams = {}; * @param {String} orderId ID of pet that needs to be fetched
var formParams = {}; * @param {function} callback the callback function, accepting three arguments: error, data, response
* data is of type: Order
*/
self.getOrderById = function(orderId, callback) {
var postBody = null;
path += createQueryString(queryParams);
var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
/** // verify the required parameter 'orderId' is set
* @returns Order if (orderId == null) {
*/ throw "Missing the required parameter 'orderId' when calling getOrderById";
var myResponse = new Order();
myResponse.constructFromObject(response);
if (callback) {
callback(myResponse, textStatus, jqXHR);
} }
});
return request; var pathParams = {
} 'orderId': orderId
};
/** var queryParams = {
* Find purchase order by ID };
* For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions var headerParams = {
* @param {String} orderId ID of pet that needs to be fetched };
* @param {function} callback the callback function var formParams = {
* @return Order };
*/
self.getOrderById = function(orderId, callback) { var contentTypes = [];
var postBody = null; var accepts = ['application/json', 'application/xml'];
var postBinaryBody = null;
var handleResponse = null;
// verify the required parameter 'orderId' is set if (callback) {
if (orderId == null) { handleResponse = function(error, data, response) {
//throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); if (!error && data) {
var errorRequiredMsg = "Missing the required parameter 'orderId' when calling getOrderById"; var result = new Order();
throw errorRequiredMsg; result.constructFromObject(data);
} callback(error, result, response);
} else {
// create path and map variables callback(error, data, response);
var basePath = 'http://petstore.swagger.io/v2'; }
// if basePath ends with a /, remove it as path starts with a leading / };
if (basePath.substring(basePath.length-1, basePath.length)=='/') { }
basePath = basePath.substring(0, basePath.length-1);
return this.apiClient.callApi(
'/store/order/{orderId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
} }
var path = basePath + replaceAll(replaceAll("/store/order/{orderId}", "\\{format\\}","json") /**
, "\\{" + "orderId" + "\\}", encodeURIComponent(orderId.toString())); * Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
var queryParams = {}; * @param {String} orderId ID of the order that needs to be deleted
var headerParams = {}; * @param {function} callback the callback function, accepting three arguments: error, data, response
var formParams = {}; */
self.deleteOrder = function(orderId, callback) {
var postBody = null;
path += createQueryString(queryParams);
var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
/** // verify the required parameter 'orderId' is set
* @returns Order if (orderId == null) {
*/ throw "Missing the required parameter 'orderId' when calling deleteOrder";
var myResponse = new Order();
myResponse.constructFromObject(response);
if (callback) {
callback(myResponse, textStatus, jqXHR);
} }
});
return request; var pathParams = {
} 'orderId': orderId
};
/** var queryParams = {
* Delete purchase order by ID };
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors var headerParams = {
* @param {String} orderId ID of the order that needs to be deleted };
* @param {function} callback the callback function var formParams = {
* @return void };
*/
self.deleteOrder = function(orderId, callback) { var contentTypes = [];
var postBody = null; var accepts = ['application/json', 'application/xml'];
var postBinaryBody = null;
var handleResponse = null;
// verify the required parameter 'orderId' is set if (callback) {
if (orderId == null) { handleResponse = function(error, data, response) {
//throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); callback(error, data, response);
var errorRequiredMsg = "Missing the required parameter 'orderId' when calling deleteOrder"; };
throw errorRequiredMsg; }
}
return this.apiClient.callApi(
// create path and map variables '/store/order/{orderId}', 'DELETE',
var basePath = 'http://petstore.swagger.io/v2'; pathParams, queryParams, headerParams, formParams, postBody,
// if basePath ends with a /, remove it as path starts with a leading / contentTypes, accepts, handleResponse
if (basePath.substring(basePath.length-1, basePath.length)=='/') { );
basePath = basePath.substring(0, basePath.length-1);
} }
var path = basePath + replaceAll(replaceAll("/store/order/{orderId}", "\\{format\\}","json")
, "\\{" + "orderId" + "\\}", encodeURIComponent(orderId.toString()));
var queryParams = {};
var headerParams = {};
var formParams = {};
};
path += createQueryString(queryParams); return StoreApi;
}));
var options = {type: "DELETE", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
if (callback) {
callback(response, textStatus, jqXHR);
}
});
return request;
}
function replaceAll (haystack, needle, replace) {
var result= haystack;
if (needle !=null && replace!=null) {
result= haystack.replace(new RegExp(needle, 'g'), replace);
}
return result;
}
function createQueryString (queryParams) {
var queryString ='';
var i = 0;
for (var queryParamName in queryParams) {
if (i==0) {
queryString += '?' ;
} else {
queryString += '&' ;
}
queryString += queryParamName + '=' + encodeURIComponent(queryParams[queryParamName]);
i++;
}
return queryString;
}
}
// export module for Node.js
if (typeof module === 'object' && module.exports) {
module.exports = StoreApi;
}

View File

@ -1,498 +1,361 @@
// require files in Node.js environment (function(root, factory) {
var $, User; if (typeof define === 'function' && define.amd) {
if (typeof module === 'object' && module.exports) { // AMD. Register as an anonymous module.
$ = require('jquery'); define(['../ApiClient', '../model/User'], factory);
User = require('../model/User.js'); } else if (typeof module === 'object' && module.exports) {
} // CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient.js'), require('../model/User.js'));
} else {
// Browser globals (root is window)
if (!root.SwaggerPetstore) {
root.SwaggerPetstore = {};
}
root.SwaggerPetstore.UserApi = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.User);
}
}(this, function(ApiClient, User) {
'use strict';
// export module for AMD var UserApi = function UserApi(apiClient) {
if ( typeof define === "function" && define.amd ) { this.apiClient = apiClient || ApiClient.default;
define(['jquery', 'User'], function($, User) {
return UserApi;
});
}
var UserApi = function UserApi() { var self = this;
var self = this;
/**
* Create user
* This can only be done by the logged in user.
* @param {User} body Created user object
* @param {function} callback the callback function
* @return void
*/
self.createUser = function(body, callback) {
var postBody = JSON.stringify(body);
var postBinaryBody = null;
// create path and map variables
var basePath = 'http://petstore.swagger.io/v2'; /**
// if basePath ends with a /, remove it as path starts with a leading / * Create user
if (basePath.substring(basePath.length-1, basePath.length)=='/') { * This can only be done by the logged in user.
basePath = basePath.substring(0, basePath.length-1); * @param {User} body Created user object
* @param {function} callback the callback function, accepting three arguments: error, data, response
*/
self.createUser = function(body, callback) {
var postBody = body;
var pathParams = {
};
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var contentTypes = [];
var accepts = ['application/json', 'application/xml'];
var handleResponse = null;
if (callback) {
handleResponse = function(error, data, response) {
callback(error, data, response);
};
}
return this.apiClient.callApi(
'/user', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
} }
var path = basePath + replaceAll(replaceAll("/user", "\\{format\\}","json")); /**
* Creates list of users with given input array
var queryParams = {}; *
var headerParams = {}; * @param {Array} body List of user object
var formParams = {}; * @param {function} callback the callback function, accepting three arguments: error, data, response
*/
self.createUsersWithArrayInput = function(body, callback) {
var postBody = body;
path += createQueryString(queryParams);
var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
if (callback) {
callback(response, textStatus, jqXHR);
} var pathParams = {
};
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var contentTypes = [];
var accepts = ['application/json', 'application/xml'];
var handleResponse = null;
if (callback) {
handleResponse = function(error, data, response) {
callback(error, data, response);
};
}
return this.apiClient.callApi(
'/user/createWithArray', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
});
return request;
}
/**
* Creates list of users with given input array
*
* @param {Array} body List of user object
* @param {function} callback the callback function
* @return void
*/
self.createUsersWithArrayInput = function(body, callback) {
var postBody = JSON.stringify(body);
var postBinaryBody = null;
// create path and map variables
var basePath = 'http://petstore.swagger.io/v2';
// if basePath ends with a /, remove it as path starts with a leading /
if (basePath.substring(basePath.length-1, basePath.length)=='/') {
basePath = basePath.substring(0, basePath.length-1);
} }
var path = basePath + replaceAll(replaceAll("/user/createWithArray", "\\{format\\}","json")); /**
* Creates list of users with given input array
var queryParams = {}; *
var headerParams = {}; * @param {Array} body List of user object
var formParams = {}; * @param {function} callback the callback function, accepting three arguments: error, data, response
*/
self.createUsersWithListInput = function(body, callback) {
var postBody = body;
path += createQueryString(queryParams);
var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
if (callback) {
callback(response, textStatus, jqXHR);
} var pathParams = {
};
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var contentTypes = [];
var accepts = ['application/json', 'application/xml'];
var handleResponse = null;
if (callback) {
handleResponse = function(error, data, response) {
callback(error, data, response);
};
}
return this.apiClient.callApi(
'/user/createWithList', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
});
return request;
}
/**
* Creates list of users with given input array
*
* @param {Array} body List of user object
* @param {function} callback the callback function
* @return void
*/
self.createUsersWithListInput = function(body, callback) {
var postBody = JSON.stringify(body);
var postBinaryBody = null;
// create path and map variables
var basePath = 'http://petstore.swagger.io/v2';
// if basePath ends with a /, remove it as path starts with a leading /
if (basePath.substring(basePath.length-1, basePath.length)=='/') {
basePath = basePath.substring(0, basePath.length-1);
} }
var path = basePath + replaceAll(replaceAll("/user/createWithList", "\\{format\\}","json")); /**
* Logs user into the system
var queryParams = {}; *
var headerParams = {}; * @param {String} username The user name for login
var formParams = {}; * @param {String} password The password for login in clear text
* @param {function} callback the callback function, accepting three arguments: error, data, response
* data is of type: String
*/
self.loginUser = function(username, password, callback) {
var postBody = null;
path += createQueryString(queryParams);
var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
if (callback) {
callback(response, textStatus, jqXHR);
} var pathParams = {
};
var queryParams = {
'username': username,
'password': password
};
var headerParams = {
};
var formParams = {
};
var contentTypes = [];
var accepts = ['application/json', 'application/xml'];
var handleResponse = null;
if (callback) {
handleResponse = function(error, data, response) {
callback(error, data, response);
};
}
return this.apiClient.callApi(
'/user/login', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
});
return request;
}
/**
* Logs user into the system
*
* @param {String} username The user name for login
* @param {String} password The password for login in clear text
* @param {function} callback the callback function
* @return String
*/
self.loginUser = function(username, password, callback) {
var postBody = null;
var postBinaryBody = null;
// create path and map variables
var basePath = 'http://petstore.swagger.io/v2';
// if basePath ends with a /, remove it as path starts with a leading /
if (basePath.substring(basePath.length-1, basePath.length)=='/') {
basePath = basePath.substring(0, basePath.length-1);
} }
var path = basePath + replaceAll(replaceAll("/user/login", "\\{format\\}","json")); /**
* Logs out current logged in user session
*
* @param {function} callback the callback function, accepting three arguments: error, data, response
*/
self.logoutUser = function(callback) {
var postBody = null;
var queryParams = {};
var headerParams = {}; var pathParams = {
var formParams = {}; };
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var contentTypes = [];
queryParams.username = username; var accepts = ['application/json', 'application/xml'];
queryParams.password = password;
path += createQueryString(queryParams); var handleResponse = null;
var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) { if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error'; handleResponse = function(error, data, response) {
callback(null, textStatus, jqXHR, error); callback(error, data, response);
};
} }
});
return this.apiClient.callApi(
request.done(function(response, textStatus, jqXHR){ '/user/logout', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
/**
* @returns String
*/
var myResponse = response;
if (callback) {
callback(myResponse, textStatus, jqXHR);
}
});
return request;
}
/**
* Logs out current logged in user session
*
* @param {function} callback the callback function
* @return void
*/
self.logoutUser = function(callback) {
var postBody = null;
var postBinaryBody = null;
// create path and map variables
var basePath = 'http://petstore.swagger.io/v2';
// if basePath ends with a /, remove it as path starts with a leading /
if (basePath.substring(basePath.length-1, basePath.length)=='/') {
basePath = basePath.substring(0, basePath.length-1);
} }
var path = basePath + replaceAll(replaceAll("/user/logout", "\\{format\\}","json")); /**
* Get user by user name
var queryParams = {}; *
var headerParams = {}; * @param {String} username The name that needs to be fetched. Use user1 for testing.
var formParams = {}; * @param {function} callback the callback function, accepting three arguments: error, data, response
* data is of type: User
*/
self.getUserByName = function(username, callback) {
var postBody = null;
path += createQueryString(queryParams);
var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
if (callback) { // verify the required parameter 'username' is set
callback(response, textStatus, jqXHR); if (username == null) {
throw "Missing the required parameter 'username' when calling getUserByName";
} }
});
return request; var pathParams = {
} 'username': username
};
/** var queryParams = {
* Get user by user name };
* var headerParams = {
* @param {String} username The name that needs to be fetched. Use user1 for testing. };
* @param {function} callback the callback function var formParams = {
* @return User };
*/
self.getUserByName = function(username, callback) { var contentTypes = [];
var postBody = null; var accepts = ['application/json', 'application/xml'];
var postBinaryBody = null;
var handleResponse = null;
// verify the required parameter 'username' is set if (callback) {
if (username == null) { handleResponse = function(error, data, response) {
//throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); if (!error && data) {
var errorRequiredMsg = "Missing the required parameter 'username' when calling getUserByName"; var result = new User();
throw errorRequiredMsg; result.constructFromObject(data);
} callback(error, result, response);
} else {
// create path and map variables callback(error, data, response);
var basePath = 'http://petstore.swagger.io/v2'; }
// if basePath ends with a /, remove it as path starts with a leading / };
if (basePath.substring(basePath.length-1, basePath.length)=='/') { }
basePath = basePath.substring(0, basePath.length-1);
return this.apiClient.callApi(
'/user/{username}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
} }
var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") /**
, "\\{" + "username" + "\\}", encodeURIComponent(username.toString())); * Updated user
* This can only be done by the logged in user.
var queryParams = {}; * @param {String} username name that need to be deleted
var headerParams = {}; * @param {User} body Updated user object
var formParams = {}; * @param {function} callback the callback function, accepting three arguments: error, data, response
*/
self.updateUser = function(username, body, callback) {
var postBody = body;
path += createQueryString(queryParams);
var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
/** // verify the required parameter 'username' is set
* @returns User if (username == null) {
*/ throw "Missing the required parameter 'username' when calling updateUser";
var myResponse = new User();
myResponse.constructFromObject(response);
if (callback) {
callback(myResponse, textStatus, jqXHR);
} }
});
return request; var pathParams = {
} 'username': username
};
/** var queryParams = {
* Updated user };
* This can only be done by the logged in user. var headerParams = {
* @param {String} username name that need to be deleted };
* @param {User} body Updated user object var formParams = {
* @param {function} callback the callback function };
* @return void
*/ var contentTypes = [];
self.updateUser = function(username, body, callback) { var accepts = ['application/json', 'application/xml'];
var postBody = JSON.stringify(body);
var postBinaryBody = null; var handleResponse = null;
if (callback) {
// verify the required parameter 'username' is set handleResponse = function(error, data, response) {
if (username == null) { callback(error, data, response);
//throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); };
var errorRequiredMsg = "Missing the required parameter 'username' when calling updateUser"; }
throw errorRequiredMsg;
} return this.apiClient.callApi(
'/user/{username}', 'PUT',
// create path and map variables pathParams, queryParams, headerParams, formParams, postBody,
var basePath = 'http://petstore.swagger.io/v2'; contentTypes, accepts, handleResponse
// if basePath ends with a /, remove it as path starts with a leading / );
if (basePath.substring(basePath.length-1, basePath.length)=='/') {
basePath = basePath.substring(0, basePath.length-1);
} }
var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") /**
, "\\{" + "username" + "\\}", encodeURIComponent(username.toString())); * Delete user
* This can only be done by the logged in user.
var queryParams = {}; * @param {String} username The name that needs to be deleted
var headerParams = {}; * @param {function} callback the callback function, accepting three arguments: error, data, response
var formParams = {}; */
self.deleteUser = function(username, callback) {
var postBody = null;
path += createQueryString(queryParams);
var options = {type: "PUT", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
if (callback) { // verify the required parameter 'username' is set
callback(response, textStatus, jqXHR); if (username == null) {
throw "Missing the required parameter 'username' when calling deleteUser";
} }
});
return request; var pathParams = {
} 'username': username
};
/** var queryParams = {
* Delete user };
* This can only be done by the logged in user. var headerParams = {
* @param {String} username The name that needs to be deleted };
* @param {function} callback the callback function var formParams = {
* @return void };
*/
self.deleteUser = function(username, callback) { var contentTypes = [];
var postBody = null; var accepts = ['application/json', 'application/xml'];
var postBinaryBody = null;
var handleResponse = null;
// verify the required parameter 'username' is set if (callback) {
if (username == null) { handleResponse = function(error, data, response) {
//throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); callback(error, data, response);
var errorRequiredMsg = "Missing the required parameter 'username' when calling deleteUser"; };
throw errorRequiredMsg; }
}
return this.apiClient.callApi(
// create path and map variables '/user/{username}', 'DELETE',
var basePath = 'http://petstore.swagger.io/v2'; pathParams, queryParams, headerParams, formParams, postBody,
// if basePath ends with a /, remove it as path starts with a leading / contentTypes, accepts, handleResponse
if (basePath.substring(basePath.length-1, basePath.length)=='/') { );
basePath = basePath.substring(0, basePath.length-1);
} }
var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json")
, "\\{" + "username" + "\\}", encodeURIComponent(username.toString()));
var queryParams = {};
var headerParams = {};
var formParams = {};
};
path += createQueryString(queryParams); return UserApi;
}));
var options = {type: "DELETE", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});
request.done(function(response, textStatus, jqXHR){
if (callback) {
callback(response, textStatus, jqXHR);
}
});
return request;
}
function replaceAll (haystack, needle, replace) {
var result= haystack;
if (needle !=null && replace!=null) {
result= haystack.replace(new RegExp(needle, 'g'), replace);
}
return result;
}
function createQueryString (queryParams) {
var queryString ='';
var i = 0;
for (var queryParamName in queryParams) {
if (i==0) {
queryString += '?' ;
} else {
queryString += '&' ;
}
queryString += queryParamName + '=' + encodeURIComponent(queryParams[queryParamName]);
i++;
}
return queryString;
}
}
// export module for Node.js
if (typeof module === 'object' && module.exports) {
module.exports = UserApi;
}

View File

@ -1,22 +1,23 @@
if (typeof module === 'object' && module.exports) { (function(factory) {
var SwaggerPetstore = {}; if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
SwaggerPetstore.User = require('./model/User.js'); define(['./ApiClient', './model/User', './model/Category', './model/Pet', './model/Tag', './model/Order', './api/UserApi', './api/StoreApi', './api/PetApi'], factory);
} else if (typeof module === 'object' && module.exports) {
SwaggerPetstore.Category = require('./model/Category.js'); // CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('./ApiClient.js'), require('./model/User.js'), require('./model/Category.js'), require('./model/Pet.js'), require('./model/Tag.js'), require('./model/Order.js'), require('./api/UserApi.js'), require('./api/StoreApi.js'), require('./api/PetApi.js'));
SwaggerPetstore.Pet = require('./model/Pet.js'); }
}(function(ApiClient, User, Category, Pet, Tag, Order, UserApi, StoreApi, PetApi) {
SwaggerPetstore.Tag = require('./model/Tag.js'); 'use strict';
SwaggerPetstore.Order = require('./model/Order.js'); return {
ApiClient: ApiClient,
User: User,
SwaggerPetstore.UserApi = require('./api/UserApi.js'); Category: Category,
Pet: Pet,
SwaggerPetstore.StoreApi = require('./api/StoreApi.js'); Tag: Tag,
Order: Order,
SwaggerPetstore.PetApi = require('./api/PetApi.js'); UserApi: UserApi,
StoreApi: StoreApi,
module.exports = SwaggerPetstore; PetApi: PetApi
} };
}));

View File

@ -1,81 +1,89 @@
// require files in Node.js environment (function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([undefined], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(undefined);
} else {
// Browser globals (root is window)
if (!root.SwaggerPetstore) {
root.SwaggerPetstore = {};
}
factory(root.SwaggerPetstore);
}
}(this, function(module) {
'use strict';
if (typeof module === 'object' && module.exports) {
}
//export module
if ( typeof define === "function" && define.amd ) {
define('Category', ['jquery'],
function($) {
return Category;
});
}
var Category = function Category() {
var self = this;
/**
* datatype: Integer
**/
self.id = null;
/**
* datatype: String
**/
self.name = null;
self.constructFromObject = function(data) {
if (!data) {
return; var Category = function Category() {
var self = this;
/**
* datatype: Integer
**/
self.id = null;
/**
* datatype: String
**/
self.name = null;
self.constructFromObject = function(data) {
if (!data) {
return;
}
self.id = data.id;
self.name = data.name;
}
/**
* @return {Integer}
**/
self.getId = function() {
return self.id;
}
/**
* @param {Integer} id
**/
self.setId = function (id) {
self.id = id;
} }
self.id = data.id; /**
* @return {String}
self.name = data.name; **/
self.getName = function() {
return self.name;
}
/**
* @param {String} name
**/
self.setName = function (name) {
self.name = name;
}
self.toJson = function () {
return JSON.stringify(self);
}
};
if (module) {
module.Category = Category;
} }
return Category;
/**
* @return {Integer}
**/
self.getId = function() {
return self.id;
}
/**
* @param {Integer} id
**/
self.setId = function (id) {
self.id = id;
}
/** }));
* @return {String}
**/
self.getName = function() {
return self.name;
}
/**
* @param {String} name
**/
self.setName = function (name) {
self.name = name;
}
self.toJson = function () {
return JSON.stringify(self);
}
}
if (typeof module === 'object' && module.exports) {
module.exports = Category;
}

View File

@ -1,11 +1,22 @@
// require files in Node.js environment (function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([undefined], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(undefined);
} else {
// Browser globals (root is window)
if (!root.SwaggerPetstore) {
root.SwaggerPetstore = {};
}
factory(root.SwaggerPetstore);
}
}(this, function(module) {
'use strict';
if (typeof module === 'object' && module.exports) {
}
//export module //export module
if ( typeof define === "function" && define.amd ) { if ( typeof define === "function" && define.amd ) {
define('StatusEnum', ['jquery'], function($) { define('StatusEnum', ['jquery'], function($) {
@ -35,162 +46,159 @@ var StatusEnum = function StatusEnum() {
} }
//export module
if ( typeof define === "function" && define.amd ) { var Order = function Order() {
define('Order', ['jquery'], var self = this;
function($) {
return Order; /**
}); * datatype: Integer
} **/
self.id = null;
/**
* datatype: Integer
**/
self.petId = null;
/**
* datatype: Integer
**/
self.quantity = null;
/**
* datatype: Date
**/
self.shipDate = null;
/**
* Order Status
* datatype: StatusEnum
**/
self.status = null;
/**
* datatype: Boolean
**/
self.complete = null;
self.constructFromObject = function(data) {
if (!data) {
return;
}
self.id = data.id;
self.petId = data.petId;
self.quantity = data.quantity;
self.shipDate = data.shipDate;
self.status = data.status;
self.complete = data.complete;
}
var Order = function Order() {
var self = this; /**
* @return {Integer}
/** **/
* datatype: Integer self.getId = function() {
**/ return self.id;
self.id = null; }
/** /**
* datatype: Integer * @param {Integer} id
**/ **/
self.petId = null; self.setId = function (id) {
self.id = id;
/**
* datatype: Integer
**/
self.quantity = null;
/**
* datatype: Date
**/
self.shipDate = null;
/**
* Order Status
* datatype: StatusEnum
**/
self.status = null;
/**
* datatype: Boolean
**/
self.complete = null;
self.constructFromObject = function(data) {
if (!data) {
return;
} }
self.id = data.id; /**
* @return {Integer}
**/
self.getPetId = function() {
return self.petId;
}
/**
* @param {Integer} petId
**/
self.setPetId = function (petId) {
self.petId = petId;
}
self.petId = data.petId; /**
* @return {Integer}
**/
self.getQuantity = function() {
return self.quantity;
}
/**
* @param {Integer} quantity
**/
self.setQuantity = function (quantity) {
self.quantity = quantity;
}
self.quantity = data.quantity; /**
* @return {Date}
**/
self.getShipDate = function() {
return self.shipDate;
}
/**
* @param {Date} shipDate
**/
self.setShipDate = function (shipDate) {
self.shipDate = shipDate;
}
self.shipDate = data.shipDate; /**
* get Order Status
* @return {StatusEnum}
**/
self.getStatus = function() {
return self.status;
}
/**
* set Order Status
* @param {StatusEnum} status
**/
self.setStatus = function (status) {
self.status = status;
}
self.status = data.status; /**
* @return {Boolean}
self.complete = data.complete; **/
self.getComplete = function() {
return self.complete;
}
/**
* @param {Boolean} complete
**/
self.setComplete = function (complete) {
self.complete = complete;
}
self.toJson = function () {
return JSON.stringify(self);
}
};
if (module) {
module.Order = Order;
} }
return Order;
/**
* @return {Integer}
**/
self.getId = function() {
return self.id;
}
/**
* @param {Integer} id
**/
self.setId = function (id) {
self.id = id;
}
/** }));
* @return {Integer}
**/
self.getPetId = function() {
return self.petId;
}
/**
* @param {Integer} petId
**/
self.setPetId = function (petId) {
self.petId = petId;
}
/**
* @return {Integer}
**/
self.getQuantity = function() {
return self.quantity;
}
/**
* @param {Integer} quantity
**/
self.setQuantity = function (quantity) {
self.quantity = quantity;
}
/**
* @return {Date}
**/
self.getShipDate = function() {
return self.shipDate;
}
/**
* @param {Date} shipDate
**/
self.setShipDate = function (shipDate) {
self.shipDate = shipDate;
}
/**
* get Order Status
* @return {StatusEnum}
**/
self.getStatus = function() {
return self.status;
}
/**
* set Order Status
* @param {StatusEnum} status
**/
self.setStatus = function (status) {
self.status = status;
}
/**
* @return {Boolean}
**/
self.getComplete = function() {
return self.complete;
}
/**
* @param {Boolean} complete
**/
self.setComplete = function (complete) {
self.complete = complete;
}
self.toJson = function () {
return JSON.stringify(self);
}
}
if (typeof module === 'object' && module.exports) {
module.exports = Order;
}

View File

@ -1,13 +1,22 @@
// require files in Node.js environment (function(root, factory) {
var Category;var Tag; if (typeof define === 'function' && define.amd) {
if (typeof module === 'object' && module.exports) { // AMD. Register as an anonymous module.
define([undefined, './Category', './Tag'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(undefined, require('./Category.js'), require('./Tag.js'));
} else {
// Browser globals (root is window)
if (!root.SwaggerPetstore) {
root.SwaggerPetstore = {};
}
factory(root.SwaggerPetstore, root.SwaggerPetstore.Category, root.SwaggerPetstore.Tag);
}
}(this, function(module, Category, Tag) {
'use strict';
Category = require('./Category.js');
Tag = require('./Tag.js');
}
//export module //export module
if ( typeof define === "function" && define.amd ) { if ( typeof define === "function" && define.amd ) {
define('StatusEnum', ['jquery'], function($) { define('StatusEnum', ['jquery'], function($) {
@ -37,164 +46,161 @@ var StatusEnum = function StatusEnum() {
} }
//export module
if ( typeof define === "function" && define.amd ) { var Pet = function Pet(photoUrls, name) {
define('Pet', ['jquery', 'Category', 'Array'], var self = this;
function($, Category, Array) {
return Pet; /**
}); * datatype: Integer
} **/
self.id = null;
/**
* datatype: Category
**/
self.category = new Category();
/**
* datatype: String
* required
**/
self.name = name;
/**
* datatype: Array
* required
**/
self.photoUrls = photoUrls;
/**
* datatype: Array
**/
self.tags = [];
/**
* pet status in the store
* datatype: StatusEnum
**/
self.status = null;
self.constructFromObject = function(data) {
if (!data) {
return;
}
self.id = data.id;
self.category.constructFromObject(data.category);
self.name = data.name;
self.photoUrls = new Array();
self.tags = new Array();
self.status = data.status;
}
var Pet = function Pet(photoUrls, name) {
var self = this; /**
* @return {Integer}
/** **/
* datatype: Integer self.getId = function() {
**/ return self.id;
self.id = null; }
/** /**
* datatype: Category * @param {Integer} id
**/ **/
self.category = new Category(); self.setId = function (id) {
self.id = id;
/**
* datatype: String
* required
**/
self.name = name;
/**
* datatype: Array
* required
**/
self.photoUrls = photoUrls;
/**
* datatype: Array
**/
self.tags = [];
/**
* pet status in the store
* datatype: StatusEnum
**/
self.status = null;
self.constructFromObject = function(data) {
if (!data) {
return;
} }
self.id = data.id; /**
* @return {Category}
**/
self.getCategory = function() {
return self.category;
}
/**
* @param {Category} category
**/
self.setCategory = function (category) {
self.category = category;
}
self.category.constructFromObject(data.category); /**
* @return {String}
**/
self.getName = function() {
return self.name;
}
/**
* @param {String} name
**/
self.setName = function (name) {
self.name = name;
}
self.name = data.name; /**
* @return {Array}
**/
self.getPhotoUrls = function() {
return self.photoUrls;
}
/**
* @param {Array} photoUrls
**/
self.setPhotoUrls = function (photoUrls) {
self.photoUrls = photoUrls;
}
self.photoUrls = new Array(); /**
* @return {Array}
**/
self.getTags = function() {
return self.tags;
}
/**
* @param {Array} tags
**/
self.setTags = function (tags) {
self.tags = tags;
}
self.tags = new Array(); /**
* get pet status in the store
self.status = data.status; * @return {StatusEnum}
**/
self.getStatus = function() {
return self.status;
}
/**
* set pet status in the store
* @param {StatusEnum} status
**/
self.setStatus = function (status) {
self.status = status;
}
self.toJson = function () {
return JSON.stringify(self);
}
};
if (module) {
module.Pet = Pet;
} }
return Pet;
/**
* @return {Integer}
**/
self.getId = function() {
return self.id;
}
/**
* @param {Integer} id
**/
self.setId = function (id) {
self.id = id;
}
/** }));
* @return {Category}
**/
self.getCategory = function() {
return self.category;
}
/**
* @param {Category} category
**/
self.setCategory = function (category) {
self.category = category;
}
/**
* @return {String}
**/
self.getName = function() {
return self.name;
}
/**
* @param {String} name
**/
self.setName = function (name) {
self.name = name;
}
/**
* @return {Array}
**/
self.getPhotoUrls = function() {
return self.photoUrls;
}
/**
* @param {Array} photoUrls
**/
self.setPhotoUrls = function (photoUrls) {
self.photoUrls = photoUrls;
}
/**
* @return {Array}
**/
self.getTags = function() {
return self.tags;
}
/**
* @param {Array} tags
**/
self.setTags = function (tags) {
self.tags = tags;
}
/**
* get pet status in the store
* @return {StatusEnum}
**/
self.getStatus = function() {
return self.status;
}
/**
* set pet status in the store
* @param {StatusEnum} status
**/
self.setStatus = function (status) {
self.status = status;
}
self.toJson = function () {
return JSON.stringify(self);
}
}
if (typeof module === 'object' && module.exports) {
module.exports = Pet;
}

View File

@ -1,81 +1,89 @@
// require files in Node.js environment (function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([undefined], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(undefined);
} else {
// Browser globals (root is window)
if (!root.SwaggerPetstore) {
root.SwaggerPetstore = {};
}
factory(root.SwaggerPetstore);
}
}(this, function(module) {
'use strict';
if (typeof module === 'object' && module.exports) {
}
//export module
if ( typeof define === "function" && define.amd ) {
define('Tag', ['jquery'],
function($) {
return Tag;
});
}
var Tag = function Tag() {
var self = this;
/**
* datatype: Integer
**/
self.id = null;
/**
* datatype: String
**/
self.name = null;
self.constructFromObject = function(data) {
if (!data) {
return; var Tag = function Tag() {
var self = this;
/**
* datatype: Integer
**/
self.id = null;
/**
* datatype: String
**/
self.name = null;
self.constructFromObject = function(data) {
if (!data) {
return;
}
self.id = data.id;
self.name = data.name;
}
/**
* @return {Integer}
**/
self.getId = function() {
return self.id;
}
/**
* @param {Integer} id
**/
self.setId = function (id) {
self.id = id;
} }
self.id = data.id; /**
* @return {String}
self.name = data.name; **/
self.getName = function() {
return self.name;
}
/**
* @param {String} name
**/
self.setName = function (name) {
self.name = name;
}
self.toJson = function () {
return JSON.stringify(self);
}
};
if (module) {
module.Tag = Tag;
} }
return Tag;
/**
* @return {Integer}
**/
self.getId = function() {
return self.id;
}
/**
* @param {Integer} id
**/
self.setId = function (id) {
self.id = id;
}
/** }));
* @return {String}
**/
self.getName = function() {
return self.name;
}
/**
* @param {String} name
**/
self.setName = function (name) {
self.name = name;
}
self.toJson = function () {
return JSON.stringify(self);
}
}
if (typeof module === 'object' && module.exports) {
module.exports = Tag;
}

View File

@ -1,210 +1,218 @@
// require files in Node.js environment (function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([undefined], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(undefined);
} else {
// Browser globals (root is window)
if (!root.SwaggerPetstore) {
root.SwaggerPetstore = {};
}
factory(root.SwaggerPetstore);
}
}(this, function(module) {
'use strict';
if (typeof module === 'object' && module.exports) {
}
var User = function User() {
var self = this;
/**
* datatype: Integer
**/
self.id = null;
/**
* datatype: String
**/
self.username = null;
/**
* datatype: String
**/
self.firstName = null;
/**
* datatype: String
**/
self.lastName = null;
/**
* datatype: String
**/
self.email = null;
/**
* datatype: String
**/
self.password = null;
/**
* datatype: String
**/
self.phone = null;
/**
* User Status
* datatype: Integer
**/
self.userStatus = null;
self.constructFromObject = function(data) {
if (!data) {
return;
}
self.id = data.id;
self.username = data.username;
self.firstName = data.firstName;
self.lastName = data.lastName;
self.email = data.email;
self.password = data.password;
self.phone = data.phone;
self.userStatus = data.userStatus;
}
/**
* @return {Integer}
**/
self.getId = function() {
return self.id;
}
//export module /**
if ( typeof define === "function" && define.amd ) { * @param {Integer} id
define('User', ['jquery'], **/
function($) { self.setId = function (id) {
return User; self.id = id;
});
}
var User = function User() {
var self = this;
/**
* datatype: Integer
**/
self.id = null;
/**
* datatype: String
**/
self.username = null;
/**
* datatype: String
**/
self.firstName = null;
/**
* datatype: String
**/
self.lastName = null;
/**
* datatype: String
**/
self.email = null;
/**
* datatype: String
**/
self.password = null;
/**
* datatype: String
**/
self.phone = null;
/**
* User Status
* datatype: Integer
**/
self.userStatus = null;
self.constructFromObject = function(data) {
if (!data) {
return;
} }
self.id = data.id; /**
* @return {String}
**/
self.getUsername = function() {
return self.username;
}
/**
* @param {String} username
**/
self.setUsername = function (username) {
self.username = username;
}
self.username = data.username; /**
* @return {String}
**/
self.getFirstName = function() {
return self.firstName;
}
/**
* @param {String} firstName
**/
self.setFirstName = function (firstName) {
self.firstName = firstName;
}
self.firstName = data.firstName; /**
* @return {String}
**/
self.getLastName = function() {
return self.lastName;
}
/**
* @param {String} lastName
**/
self.setLastName = function (lastName) {
self.lastName = lastName;
}
self.lastName = data.lastName; /**
* @return {String}
**/
self.getEmail = function() {
return self.email;
}
/**
* @param {String} email
**/
self.setEmail = function (email) {
self.email = email;
}
self.email = data.email; /**
* @return {String}
**/
self.getPassword = function() {
return self.password;
}
/**
* @param {String} password
**/
self.setPassword = function (password) {
self.password = password;
}
self.password = data.password; /**
* @return {String}
**/
self.getPhone = function() {
return self.phone;
}
/**
* @param {String} phone
**/
self.setPhone = function (phone) {
self.phone = phone;
}
self.phone = data.phone; /**
* get User Status
self.userStatus = data.userStatus; * @return {Integer}
**/
self.getUserStatus = function() {
return self.userStatus;
}
/**
* set User Status
* @param {Integer} userStatus
**/
self.setUserStatus = function (userStatus) {
self.userStatus = userStatus;
}
self.toJson = function () {
return JSON.stringify(self);
}
};
if (module) {
module.User = User;
} }
return User;
/**
* @return {Integer}
**/
self.getId = function() {
return self.id;
}
/**
* @param {Integer} id
**/
self.setId = function (id) {
self.id = id;
}
/** }));
* @return {String}
**/
self.getUsername = function() {
return self.username;
}
/**
* @param {String} username
**/
self.setUsername = function (username) {
self.username = username;
}
/**
* @return {String}
**/
self.getFirstName = function() {
return self.firstName;
}
/**
* @param {String} firstName
**/
self.setFirstName = function (firstName) {
self.firstName = firstName;
}
/**
* @return {String}
**/
self.getLastName = function() {
return self.lastName;
}
/**
* @param {String} lastName
**/
self.setLastName = function (lastName) {
self.lastName = lastName;
}
/**
* @return {String}
**/
self.getEmail = function() {
return self.email;
}
/**
* @param {String} email
**/
self.setEmail = function (email) {
self.email = email;
}
/**
* @return {String}
**/
self.getPassword = function() {
return self.password;
}
/**
* @param {String} password
**/
self.setPassword = function (password) {
self.password = password;
}
/**
* @return {String}
**/
self.getPhone = function() {
return self.phone;
}
/**
* @param {String} phone
**/
self.setPhone = function (phone) {
self.phone = phone;
}
/**
* get User Status
* @return {Integer}
**/
self.getUserStatus = function() {
return self.userStatus;
}
/**
* set User Status
* @param {Integer} userStatus
**/
self.setUserStatus = function (userStatus) {
self.userStatus = userStatus;
}
self.toJson = function () {
return JSON.stringify(self);
}
}
if (typeof module === 'object' && module.exports) {
module.exports = User;
}

View File

@ -0,0 +1,69 @@
if (typeof module === 'object' && module.exports) {
var expect = require('expect.js');
var SwaggerPetstore = require('../src/index');
}
var apiClient = SwaggerPetstore.ApiClient.default;
describe('ApiClient', function() {
describe('defaults', function() {
it('should have correct default values with the default API client', function() {
expect(apiClient).to.be.ok();
expect(apiClient.basePath).to.be('http://petstore.swagger.io/v2');
});
it('should have correct default values with new API client and can customize it', function() {
var newClient = new SwaggerPetstore.ApiClient;
expect(newClient.basePath).to.be('http://petstore.swagger.io/v2');
expect(newClient.buildUrl('/abc', {})).to.be('http://petstore.swagger.io/v2/abc');
newClient.basePath = 'http://example.com';
expect(newClient.basePath).to.be('http://example.com');
expect(newClient.buildUrl('/abc', {})).to.be('http://example.com/abc');
});
});
describe('#paramToString', function() {
it('should return empty string for null and undefined', function() {
expect(apiClient.paramToString(null)).to.be('');
expect(apiClient.paramToString(undefined)).to.be('');
});
it('should return string', function() {
expect(apiClient.paramToString('')).to.be('');
expect(apiClient.paramToString('abc')).to.be('abc');
expect(apiClient.paramToString(123)).to.be('123');
});
});
describe('#buildUrl', function() {
it('should work without path parameters in the path', function() {
expect(apiClient.buildUrl('/abc', {})).to
.be('http://petstore.swagger.io/v2/abc');
expect(apiClient.buildUrl('/abc/def?ok', {id: 123})).to
.be('http://petstore.swagger.io/v2/abc/def?ok');
});
it('should work with path parameters in the path', function() {
expect(apiClient.buildUrl('/{id}', {id: 123})).to
.be('http://petstore.swagger.io/v2/123');
expect(apiClient.buildUrl('/abc/{id}/{name}?ok', {id: 456, name: 'a b'})).to.
be('http://petstore.swagger.io/v2/abc/456/a%20b?ok');
});
});
describe('#isJsonMime', function() {
it('should return true for JSON MIME', function() {
expect(apiClient.isJsonMime('application/json')).to.be(true);
expect(apiClient.isJsonMime('application/json; charset=UTF8')).to.be(true);
expect(apiClient.isJsonMime('APPLICATION/JSON')).to.be(true);
});
it('should return false for non-JSON MIME', function() {
expect(apiClient.isJsonMime('')).to.be(false);
expect(apiClient.isJsonMime('text/plain')).to.be(false);
expect(apiClient.isJsonMime('application/xml')).to.be(false);
expect(apiClient.isJsonMime('application/jsonp')).to.be(false);
});
});
});

View File

@ -1,25 +1,21 @@
if (typeof module === 'object' && module.exports) { if (typeof module === 'object' && module.exports) {
var expect = require('expect.js'); var expect = require('expect.js');
var requireApiWithMocks = require('../helper.js').requireApiWithMocks; var SwaggerPetstore = require('../../src/index');
var PetApi = requireApiWithMocks('PetApi');
var Pet = require('../../src/model/Pet');
var Category = require('../../src/model/Category');
var Tag = require('../../src/model/Tag');
} }
var api; var api;
beforeEach(function() { beforeEach(function() {
api = new PetApi(); api = new SwaggerPetstore.PetApi();
}); });
var createRandomPet = function() { var createRandomPet = function() {
var id = new Date().getTime(); var id = new Date().getTime();
var pet = new Pet(); var pet = new SwaggerPetstore.Pet();
pet.setId(id); pet.setId(id);
pet.setName("gorilla" + id); pet.setName("gorilla" + id);
var category = new Category(); var category = new SwaggerPetstore.Category();
category.setName("really-happy"); category.setName("really-happy");
pet.setCategory(category); pet.setCategory(category);
@ -31,13 +27,17 @@ var createRandomPet = function() {
}; };
describe('PetApi', function() { describe('PetApi', function() {
it('should create and get pet', function (done) { it('should create and get pet', function(done) {
var pet = createRandomPet(); var pet = createRandomPet();
api.addPet(pet).then(function() { api.addPet(pet, function(error) {
api.getPetById(pet.id, function(fetched, textStatus, jqXHR, error) { if (error) throw error;
if (error) throw error;
api.getPetById(pet.id, function(error, fetched, response) {
if (error) throw error;
expect(response.status).to.be(200);
expect(response.ok).to.be(true);
expect(response.get('Content-Type')).to.be('application/json');
expect(textStatus).to.be('success');
expect(fetched).to.be.ok(); expect(fetched).to.be.ok();
expect(fetched.id).to.be(pet.id); expect(fetched.id).to.be(pet.id);
expect(fetched.getCategory()).to.be.ok(); expect(fetched.getCategory()).to.be.ok();
@ -46,8 +46,6 @@ describe('PetApi', function() {
api.deletePet(pet.id); api.deletePet(pet.id);
done(); done();
}); });
}, function(jqXHR, textStatus, errorThrown) {
throw errorThrown || textStatus;
}); });
}); });
}); });

View File

@ -1,19 +0,0 @@
var mockrequire = require('mockrequire');
var jquery = require('jquery');
var domino = require('domino');
var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
var window = domino.createWindow();
var $ = jquery(window);
$.support.cors = true;
$.ajaxSettings.xhr = function() {
return new XMLHttpRequest();
};
var requireApiWithMocks = function(path) {
return mockrequire('../src/api/' + path, {
'jquery': $
});
};
exports.requireApiWithMocks = requireApiWithMocks;

View File

@ -10,7 +10,6 @@
<script src="https://cdn.rawgit.com/jquery/jquery/2.1.4/dist/jquery.min.js"></script> <script src="https://cdn.rawgit.com/jquery/jquery/2.1.4/dist/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/Automattic/expect.js/0.3.1/index.js"></script> <script src="https://cdn.rawgit.com/Automattic/expect.js/0.3.1/index.js"></script>
<script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script> <script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
<script> <script>
mocha.setup({ mocha.setup({
ui: 'bdd', ui: 'bdd',
@ -18,12 +17,20 @@
}); });
</script> </script>
<script src="https://cdn.rawgit.com/stephanebachelier/superagent-dist/1.6.1/superagent.js"></script>
<script src="../src/model/Category.js"></script> <script src="../src/model/Category.js"></script>
<script src="../src/model/Tag.js"></script> <script src="../src/model/Tag.js"></script>
<script src="../src/model/Pet.js"></script> <script src="../src/model/Pet.js"></script>
<script src="../src/model/User.js"></script> <script src="../src/model/User.js"></script>
<script src="../src/ApiClient.js"></script>
<script src="../src/api/PetApi.js"></script> <script src="../src/api/PetApi.js"></script>
<script src="ApiClientTest.js"></script>
<script src="api/PetApiTest.js"></script> <script src="api/PetApiTest.js"></script>
<script> <script>
mocha.checkLeaks(); mocha.checkLeaks();
mocha.globals(['jQuery']); mocha.globals(['jQuery']);

File diff suppressed because it is too large Load Diff