From 6efbde5691c7230a65f0d467efb6c35d7800b5b7 Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 19 Jan 2016 10:46:20 +0800 Subject: [PATCH] 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` --- .../languages/JavascriptClientCodegen.java | 3 + .../resources/Javascript/ApiClient.mustache | 146 ++ .../main/resources/Javascript/api.mustache | 201 +-- .../main/resources/Javascript/index.mustache | 27 +- .../main/resources/Javascript/model.mustache | 144 +- .../resources/Javascript/package.mustache | 7 +- .../client/petstore/javascript/package.json | 7 +- .../petstore/javascript/src/ApiClient.js | 146 ++ .../petstore/javascript/src/api/PetApi.js | 895 +++++------ .../petstore/javascript/src/api/StoreApi.js | 442 +++--- .../petstore/javascript/src/api/UserApi.js | 775 ++++----- .../client/petstore/javascript/src/index.js | 45 +- .../petstore/javascript/src/model/Category.js | 150 +- .../petstore/javascript/src/model/Order.js | 312 ++-- .../petstore/javascript/src/model/Pet.js | 320 ++-- .../petstore/javascript/src/model/Tag.js | 150 +- .../petstore/javascript/src/model/User.js | 390 ++--- .../petstore/javascript/test/ApiClientTest.js | 69 + .../javascript/test/api/PetApiTest.js | 28 +- .../client/petstore/javascript/test/helper.js | 19 - .../petstore/javascript/test/run_tests.html | 9 +- .../petstore/javascript/test/superagent.js | 1396 +++++++++++++++++ 22 files changed, 3575 insertions(+), 2106 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache create mode 100644 samples/client/petstore/javascript/src/ApiClient.js create mode 100644 samples/client/petstore/javascript/test/ApiClientTest.js delete mode 100644 samples/client/petstore/javascript/test/helper.js create mode 100644 samples/client/petstore/javascript/test/superagent.js diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java index 94eae2cd94a..2620efe209d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java @@ -134,6 +134,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo typeMapping.put("double", "Number"); typeMapping.put("number", "Number"); typeMapping.put("DateTime", "Date"); + // binary not supported in JavaScript client right now, using Object as a workaround + typeMapping.put("binary", "Object"); 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("index.mustache", sourceFolder, "index.js")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", sourceFolder, "ApiClient.js")); } @Override diff --git a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache new file mode 100644 index 00000000000..2f85250694d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache @@ -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; +})); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache index 9957fc4e2c5..a61e4912596 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache @@ -1,125 +1,86 @@ -// require files in Node.js environment -var ${{#imports}}, {{import}}{{/imports}}; -if (typeof module === 'object' && module.exports) { - $ = require('jquery');{{#imports}} - {{import}} = require('../model/{{import}}.js');{{/imports}} -} - -// export module for AMD -if ( typeof define === "function" && define.amd ) { - define(['jquery'{{#imports}}, '{{import}}'{{/imports}}], function(${{#imports}}, {{import}}{{/imports}}) { - return {{classname}}; - }); -} - -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); +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient'{{#imports}}, '../model/{{import}}'{{/imports}}], factory); + } 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}}); + } else { + // Browser globals (root is window) + if (!root.{{moduleName}}) { + root.{{moduleName}} = {}; } - - 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; + root.{{moduleName}}.{{classname}} = factory(root.{{moduleName}}.ApiClient{{#imports}}, root.{{moduleName}}.{{import}}{{/imports}}); } - {{/operation}} - {{/operations}} +}(this, function(ApiClient{{#imports}}, {{import}}{{/imports}}) { + 'use strict'; - function replaceAll (haystack, needle, replace) { - var result= haystack; - if (needle !=null && replace!=null) { - result= haystack.replace(new RegExp(needle, 'g'), replace); - } - return result; - } + var {{classname}} = function {{classname}}(apiClient) { + this.apiClient = apiClient || ApiClient.default; - 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; - } -} + var self = this; + {{#operations}} + {{#operation}} + /** + * {{summary}} + * {{notes}} + {{#allParams}} * @param {{=<% %>=}}{<% dataType %>} <%={{ }}=%> {{paramName}} {{description}} + {{/allParams}} * @param {function} callback the callback function, accepting three arguments: error, data, response{{#returnType}} + * data is of type: {{{returnType}}}{{/returnType}} + */ + self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}callback) { + var postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + 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) { - module.exports = {{classname}}; -} + {{=< >=}} + var pathParams = {<#pathParams> + '': <#hasMore>, + }; + var queryParams = {<#queryParams> + '': <#hasMore>, + }; + var headerParams = {<#headerParams> + '': <#hasMore>, + }; + var formParams = {<#formParams> + '': <#hasMore>, + }; + + var contentTypes = [<#consumes>''<#hasMore>, ]; + var accepts = [<#produces>''<#hasMore>, ]; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) {<#returnType><#returnTypeIsPrimitive> + callback(error, data, response);<^returnTypeIsPrimitive><#isListContainer> + // TODO: support deserializing array of models + callback(error, data, response);<^isListContainer> + if (!error && data) { + var result = new <&returnType>(); + result.constructFromObject(data); + callback(error, result, response); + } else { + callback(error, data, response); + }<^returnType> + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '<&path>', '', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + <={{ }}=> + } + {{/operation}} + {{/operations}} + }; + + return {{classname}}; +})); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/index.mustache b/modules/swagger-codegen/src/main/resources/Javascript/index.mustache index a0207a6cc91..7bb0329fa01 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/index.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/index.mustache @@ -1,10 +1,17 @@ -if (typeof module === 'object' && module.exports) { - var {{moduleName}} = {}; - {{#models}} - {{moduleName}}.{{importPath}} = require('./model/{{importPath}}.js'); - {{/models}} - {{#apiInfo}}{{#apis}} - {{moduleName}}.{{importPath}} = require('./api/{{importPath}}.js'); - {{/apis}}{{/apiInfo}} - module.exports = {{moduleName}}; -} \ No newline at end of file +(function(factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['./ApiClient'{{#models}}, './model/{{importPath}}'{{/models}}{{#apiInfo}}{{#apis}}, './api/{{importPath}}'{{/apis}}{{/apiInfo}}], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('./ApiClient.js'){{#models}}, require('./model/{{importPath}}.js'){{/models}}{{#apiInfo}}{{#apis}}, require('./api/{{importPath}}.js'){{/apis}}{{/apiInfo}}); + } +}(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}} + }; +})); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/model.mustache b/modules/swagger-codegen/src/main/resources/Javascript/model.mustache index 0588d03a8c1..9f265c89cf7 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/model.mustache @@ -1,75 +1,79 @@ -// require files in Node.js environment -{{#imports}} -var {{import}};{{/imports}} -if (typeof module === 'object' && module.exports) { - {{#imports}} - {{import}} = require('./{{import}}.js');{{/imports}} -} - -{{#models}}{{#model}} -{{#vars}}{{#isEnum}}{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} -{{>enumClass}}{{/items}}*/{{/items.isEnum}}{{/vars}} - -//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; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([undefined{{#imports}}, './{{import}}'{{/imports}}], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(undefined{{#imports}}, require('./{{import}}.js'){{/imports}}); + } else { + // Browser globals (root is window) + if (!root.{{moduleName}}) { + root.{{moduleName}} = {}; } + 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}} - 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}} + + 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}} - /**{{#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 (typeof module === 'object' && module.exports) { - module.exports = {{classname}}; -} -{{/model}} -{{/models}} + return {{classname}}; + {{/model}} + {{/models}} +})); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/package.mustache b/modules/swagger-codegen/src/main/resources/Javascript/package.mustache index c77ee835709..1e7650a1ba1 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/package.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/package.mustache @@ -8,13 +8,10 @@ "test": "./node_modules/mocha/bin/mocha --recursive" }, "dependencies": { - "jquery": "~2.1.4" + "superagent": "^1.6.1" }, "devDependencies": { "mocha": "~2.3.4", - "expect.js": "~0.3.1", - "mockrequire": "~0.0.5", - "domino": "~1.0.20", - "xmlhttprequest": "~1.8.0" + "expect.js": "~0.3.1" } } diff --git a/samples/client/petstore/javascript/package.json b/samples/client/petstore/javascript/package.json index 6810fd633de..fe470da8b27 100644 --- a/samples/client/petstore/javascript/package.json +++ b/samples/client/petstore/javascript/package.json @@ -8,13 +8,10 @@ "test": "./node_modules/mocha/bin/mocha --recursive" }, "dependencies": { - "jquery": "~2.1.4" + "superagent": "^1.6.1" }, "devDependencies": { "mocha": "~2.3.4", - "expect.js": "~0.3.1", - "mockrequire": "~0.0.5", - "domino": "~1.0.20", - "xmlhttprequest": "~1.8.0" + "expect.js": "~0.3.1" } } diff --git a/samples/client/petstore/javascript/src/ApiClient.js b/samples/client/petstore/javascript/src/ApiClient.js new file mode 100644 index 00000000000..8138225e2b2 --- /dev/null +++ b/samples/client/petstore/javascript/src/ApiClient.js @@ -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; +})); diff --git a/samples/client/petstore/javascript/src/api/PetApi.js b/samples/client/petstore/javascript/src/api/PetApi.js index 3b6d9c5b4c6..b6c1163111f 100644 --- a/samples/client/petstore/javascript/src/api/PetApi.js +++ b/samples/client/petstore/javascript/src/api/PetApi.js @@ -1,527 +1,462 @@ -// require files in Node.js environment -var $, Pet; -if (typeof module === 'object' && module.exports) { - $ = require('jquery'); - Pet = require('../model/Pet.js'); -} +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient', '../model/Pet'], factory); + } 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 -if ( typeof define === "function" && define.amd ) { - define(['jquery', 'Pet'], function($, Pet) { - return PetApi; - }); -} + var PetApi = function PetApi(apiClient) { + this.apiClient = apiClient || ApiClient.default; -var PetApi = function PetApi() { - 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; + var self = this; - // 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); + + /** + * Update an existing pet + * + * @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")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - 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){ + /** + * 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, accepting three arguments: error, data, response + */ + self.addPet = function(body, callback) { + var postBody = body; - 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")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - 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){ + /** + * 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, accepting three arguments: error, data, response + * data is of type: Array + */ + self.findPetsByStatus = function(status, callback) { + var postBody = null; - 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 formParams = {}; + + var pathParams = { + }; + var queryParams = { + 'tags': tags + }; + var headerParams = { + }; + var formParams = { + }; - - queryParams.status = status; - - - + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; - 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){ + var handleResponse = null; if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); + handleResponse = function(error, data, response) { + // TODO: support deserializing array of models + callback(error, data, response); + }; } - }); - - request.done(function(response, textStatus, jqXHR){ + + return this.apiClient.callApi( + '/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")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - queryParams.tags = tags; - - - - - 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){ + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param {Integer} petId ID of pet that needs to be fetched + * @param {function} callback the callback function, accepting three arguments: error, data, response + * data is of type: Pet + */ + self.getPetById = function(petId, callback) { + var postBody = null; - /** - * @returns Array - */ - - var myResponse = new Array(); - myResponse.constructFromObject(response); - if (callback) { - callback(myResponse, textStatus, jqXHR); + // verify the required parameter 'petId' is set + if (petId == null) { + throw "Missing the required parameter 'petId' when calling getPetById"; } - }); - - return request; - } - - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param {Integer} petId ID of pet that needs to be fetched - * @param {function} callback the callback function - * @return Pet - */ - self.getPetById = function(petId, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - //throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); - var errorRequiredMsg = "Missing the required parameter 'petId' when calling getPetById"; - throw errorRequiredMsg; - } - - // 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 pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + if (!error && data) { + var result = new Pet(); + result.constructFromObject(data); + callback(error, result, response); + } else { + callback(error, data, response); + } + }; + } + + 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())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - 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){ + /** + * Updates a pet in the store with form data + * + * @param {String} petId ID of pet that needs to be updated + * @param {String} name Updated name of the pet + * @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; - /** - * @returns Pet - */ - - var myResponse = new Pet(); - myResponse.constructFromObject(response); - if (callback) { - callback(myResponse, textStatus, jqXHR); + // verify the required parameter 'petId' is set + if (petId == null) { + throw "Missing the required parameter 'petId' when calling updatePetWithForm"; } - }); - - return request; - } - - /** - * Updates a pet in the store with form data - * - * @param {String} petId ID of pet that needs to be updated - * @param {String} name Updated name of the pet - * @param {String} status Updated status of the pet - * @param {function} callback the callback function - * @return void - */ - self.updatePetWithForm = function(petId, name, status, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - //throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); - var errorRequiredMsg = "Missing the required parameter 'petId' when calling updatePetWithForm"; - throw errorRequiredMsg; - } - - // 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 pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + 'name': name, + 'status': status + }; + + var contentTypes = ['application/x-www-form-urlencoded']; + 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/{petId}', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") -, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - 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){ + /** + * Deletes a pet + * + * @param {Integer} petId Pet id to delete + * @param {String} apiKey + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.deletePet = function(petId, apiKey, callback) { + var postBody = null; - if (callback) { - callback(response, textStatus, jqXHR); + // verify the required parameter 'petId' is set + if (petId == null) { + throw "Missing the required parameter 'petId' when calling deletePet"; } - }); - - return request; - } - - /** - * Deletes a pet - * - * @param {Integer} petId Pet id to delete - * @param {String} apiKey - * @param {function} callback the callback function - * @return void - */ - self.deletePet = function(petId, apiKey, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - //throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); - var errorRequiredMsg = "Missing the required parameter 'petId' when calling deletePet"; - throw errorRequiredMsg; - } - - // 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 pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + 'api_key': apiKey + }; + 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( + '/pet/{petId}', 'DELETE', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") -, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - if (apiKey != null) - headerParams.put("api_key", apiKey); - - - - 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){ + /** + * uploads an image + * + * @param {Integer} petId ID of pet to update + * @param {String} additionalMetadata Additional data to pass to server + * @param {File} file file to upload + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.uploadFile = function(petId, additionalMetadata, file, callback) { + var postBody = null; - if (callback) { - callback(response, textStatus, jqXHR); + // verify the required parameter 'petId' is set + if (petId == null) { + throw "Missing the required parameter 'petId' when calling uploadFile"; } - }); - - return request; - } - - /** - * uploads an image - * - * @param {Integer} petId ID of pet to update - * @param {String} additionalMetadata Additional data to pass to server - * @param {File} file file to upload - * @param {function} callback the callback function - * @return void - */ - self.uploadFile = function(petId, additionalMetadata, file, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - //throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); - var errorRequiredMsg = "Missing the required parameter 'petId' when calling uploadFile"; - throw errorRequiredMsg; - } - - // 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 pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + 'additionalMetadata': additionalMetadata, + 'file': file + }; + + var contentTypes = ['multipart/form-data']; + 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/{petId}/uploadImage', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/pet/{petId}/uploadImage", "\\{format\\}","json") -, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - 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){ + /** + * Fake endpoint to test byte array return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param {Integer} petId ID of pet that needs to be fetched + * @param {function} callback the callback function, accepting three arguments: error, data, response + * data is of type: Object + */ + self.getPetByIdWithByteArray = function(petId, callback) { + var postBody = null; - if (callback) { - callback(response, textStatus, jqXHR); + // verify the required parameter 'petId' is set + if (petId == null) { + throw "Missing the required parameter 'petId' when calling getPetByIdWithByteArray"; } - }); - - 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; - } + + var pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; - 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; - } -} + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; -// export module for Node.js -if (typeof module === 'object' && module.exports) { - module.exports = PetApi; -} + var handleResponse = null; + if (callback) { + 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; +})); diff --git a/samples/client/petstore/javascript/src/api/StoreApi.js b/samples/client/petstore/javascript/src/api/StoreApi.js index e52a3105964..28928fd40c2 100644 --- a/samples/client/petstore/javascript/src/api/StoreApi.js +++ b/samples/client/petstore/javascript/src/api/StoreApi.js @@ -1,286 +1,206 @@ -// require files in Node.js environment -var $, Order; -if (typeof module === 'object' && module.exports) { - $ = require('jquery'); - Order = require('../model/Order.js'); -} +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient', '../model/Order'], factory); + } 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 -if ( typeof define === "function" && define.amd ) { - define(['jquery', 'Order'], function($, Order) { - return StoreApi; - }); -} + var StoreApi = function StoreApi(apiClient) { + this.apiClient = apiClient || ApiClient.default; -var StoreApi = function StoreApi() { - var self = this; - - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @param {function} callback the callback function - * @return Object - */ - self.getInventory = function(callback) { - var postBody = null; - var postBinaryBody = null; + var self = this; - // 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); + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @param {function} callback the callback function, accepting three arguments: error, data, response + * data is of type: Object + */ + 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 formParams = {}; + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; - - - + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; - 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){ + var handleResponse = null; if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); + handleResponse = function(error, data, response) { + if (!error && data) { + var result = new Order(); + result.constructFromObject(data); + callback(error, result, response); + } else { + callback(error, data, response); + } + }; } - }); - - request.done(function(response, textStatus, jqXHR){ + + return this.apiClient.callApi( + '/store/order', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); - /** - * @returns Object - */ - 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")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - 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){ + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param {String} orderId ID of pet that needs to be fetched + * @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; - /** - * @returns Order - */ - - var myResponse = new Order(); - myResponse.constructFromObject(response); - if (callback) { - callback(myResponse, textStatus, jqXHR); + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw "Missing the required parameter 'orderId' when calling getOrderById"; } - }); - - return request; - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param {String} orderId ID of pet that needs to be fetched - * @param {function} callback the callback function - * @return Order - */ - self.getOrderById = function(orderId, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - //throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); - var errorRequiredMsg = "Missing the required parameter 'orderId' when calling getOrderById"; - throw errorRequiredMsg; - } - - // 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 pathParams = { + 'orderId': orderId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + if (!error && data) { + var result = new Order(); + result.constructFromObject(data); + callback(error, result, response); + } else { + callback(error, data, response); + } + }; + } + + 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())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - 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){ + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param {String} orderId ID of the order that needs to be deleted + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.deleteOrder = function(orderId, callback) { + var postBody = null; - /** - * @returns Order - */ - - var myResponse = new Order(); - myResponse.constructFromObject(response); - if (callback) { - callback(myResponse, textStatus, jqXHR); + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw "Missing the required parameter 'orderId' when calling deleteOrder"; } - }); - - return request; - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param {String} orderId ID of the order that needs to be deleted - * @param {function} callback the callback function - * @return void - */ - self.deleteOrder = function(orderId, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - //throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); - var errorRequiredMsg = "Missing the required parameter 'orderId' when calling deleteOrder"; - throw errorRequiredMsg; - } - - // 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 pathParams = { + 'orderId': orderId + }; + 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/order/{orderId}', 'DELETE', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/store/order/{orderId}", "\\{format\\}","json") -, "\\{" + "orderId" + "\\}", encodeURIComponent(orderId.toString())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - + }; - 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) { - 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; -} + return StoreApi; +})); diff --git a/samples/client/petstore/javascript/src/api/UserApi.js b/samples/client/petstore/javascript/src/api/UserApi.js index 148e6171ed4..656bf56dd86 100644 --- a/samples/client/petstore/javascript/src/api/UserApi.js +++ b/samples/client/petstore/javascript/src/api/UserApi.js @@ -1,498 +1,361 @@ -// require files in Node.js environment -var $, User; -if (typeof module === 'object' && module.exports) { - $ = require('jquery'); - User = require('../model/User.js'); -} +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient', '../model/User'], factory); + } 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 -if ( typeof define === "function" && define.amd ) { - define(['jquery', 'User'], function($, User) { - return UserApi; - }); -} + var UserApi = function UserApi(apiClient) { + this.apiClient = apiClient || ApiClient.default; -var UserApi = function UserApi() { - 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; + var self = this; - // 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); + + /** + * Create user + * This can only be done by the logged in user. + * @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")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - 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){ + /** + * Creates list of users with given input array + * + * @param {Array} body List of user object + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.createUsersWithArrayInput = function(body, callback) { + var postBody = body; - 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")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - 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){ + /** + * Creates list of users with given input array + * + * @param {Array} body List of user object + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.createUsersWithListInput = function(body, callback) { + var postBody = body; - 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")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - 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){ + /** + * 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, accepting three arguments: error, data, response + * data is of type: String + */ + self.loginUser = function(username, password, callback) { + var postBody = null; - 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 formParams = {}; + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; - - queryParams.username = username; - - queryParams.password = password; - - - + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; - 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){ + var handleResponse = null; if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); + handleResponse = function(error, data, response) { + callback(error, data, response); + }; } - }); - - request.done(function(response, textStatus, jqXHR){ + + return this.apiClient.callApi( + '/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")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - 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){ + /** + * Get user by user name + * + * @param {String} username The name that needs to be fetched. Use user1 for testing. + * @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; - if (callback) { - callback(response, textStatus, jqXHR); + // verify the required parameter 'username' is set + if (username == null) { + throw "Missing the required parameter 'username' when calling getUserByName"; } - }); - - return request; - } - - /** - * Get user by user name - * - * @param {String} username The name that needs to be fetched. Use user1 for testing. - * @param {function} callback the callback function - * @return User - */ - self.getUserByName = function(username, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - //throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); - var errorRequiredMsg = "Missing the required parameter 'username' when calling getUserByName"; - throw errorRequiredMsg; - } - - // 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 pathParams = { + 'username': username + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + if (!error && data) { + var result = new User(); + result.constructFromObject(data); + callback(error, result, response); + } else { + callback(error, data, response); + } + }; + } + + 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())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - 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){ + /** + * Updated user + * This can only be done by the logged in user. + * @param {String} username name that need to be deleted + * @param {User} body Updated user object + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.updateUser = function(username, body, callback) { + var postBody = body; - /** - * @returns User - */ - - var myResponse = new User(); - myResponse.constructFromObject(response); - if (callback) { - callback(myResponse, textStatus, jqXHR); + // verify the required parameter 'username' is set + if (username == null) { + throw "Missing the required parameter 'username' when calling updateUser"; } - }); - - return request; - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param {String} username name that need to be deleted - * @param {User} body Updated user object - * @param {function} callback the callback function - * @return void - */ - self.updateUser = function(username, body, callback) { - var postBody = JSON.stringify(body); - var postBinaryBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - //throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); - var errorRequiredMsg = "Missing the required parameter 'username' when calling updateUser"; - throw errorRequiredMsg; - } - - // 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 pathParams = { + 'username': username + }; + 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/{username}', 'PUT', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") -, "\\{" + "username" + "\\}", encodeURIComponent(username.toString())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - 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){ + /** + * Delete user + * This can only be done by the logged in user. + * @param {String} username The name that needs to be deleted + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.deleteUser = function(username, callback) { + var postBody = null; - if (callback) { - callback(response, textStatus, jqXHR); + // verify the required parameter 'username' is set + if (username == null) { + throw "Missing the required parameter 'username' when calling deleteUser"; } - }); - - return request; - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param {String} username The name that needs to be deleted - * @param {function} callback the callback function - * @return void - */ - self.deleteUser = function(username, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - //throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); - var errorRequiredMsg = "Missing the required parameter 'username' when calling deleteUser"; - throw errorRequiredMsg; - } - - // 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 pathParams = { + 'username': username + }; + 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/{username}', 'DELETE', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") -, "\\{" + "username" + "\\}", encodeURIComponent(username.toString())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - + }; - 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) { - 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; -} + return UserApi; +})); diff --git a/samples/client/petstore/javascript/src/index.js b/samples/client/petstore/javascript/src/index.js index b772f6024dc..725eb486075 100644 --- a/samples/client/petstore/javascript/src/index.js +++ b/samples/client/petstore/javascript/src/index.js @@ -1,22 +1,23 @@ -if (typeof module === 'object' && module.exports) { - var SwaggerPetstore = {}; - - SwaggerPetstore.User = require('./model/User.js'); - - SwaggerPetstore.Category = require('./model/Category.js'); - - SwaggerPetstore.Pet = require('./model/Pet.js'); - - SwaggerPetstore.Tag = require('./model/Tag.js'); - - SwaggerPetstore.Order = require('./model/Order.js'); - - - SwaggerPetstore.UserApi = require('./api/UserApi.js'); - - SwaggerPetstore.StoreApi = require('./api/StoreApi.js'); - - SwaggerPetstore.PetApi = require('./api/PetApi.js'); - - module.exports = SwaggerPetstore; -} \ No newline at end of file +(function(factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + 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) { + // 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')); + } +}(function(ApiClient, User, Category, Pet, Tag, Order, UserApi, StoreApi, PetApi) { + 'use strict'; + + return { + ApiClient: ApiClient, + User: User, + Category: Category, + Pet: Pet, + Tag: Tag, + Order: Order, + UserApi: UserApi, + StoreApi: StoreApi, + PetApi: PetApi + }; +})); diff --git a/samples/client/petstore/javascript/src/model/Category.js b/samples/client/petstore/javascript/src/model/Category.js index ff40497a61a..6b302a32f30 100644 --- a/samples/client/petstore/javascript/src/model/Category.js +++ b/samples/client/petstore/javascript/src/model/Category.js @@ -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; - - self.name = data.name; + /** + * @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 (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; -} +})); diff --git a/samples/client/petstore/javascript/src/model/Order.js b/samples/client/petstore/javascript/src/model/Order.js index 3cf2335b535..9f641242bf8 100644 --- a/samples/client/petstore/javascript/src/model/Order.js +++ b/samples/client/petstore/javascript/src/model/Order.js @@ -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 if ( typeof define === "function" && define.amd ) { define('StatusEnum', ['jquery'], function($) { @@ -35,162 +46,159 @@ var StatusEnum = function StatusEnum() { } -//export module -if ( typeof define === "function" && define.amd ) { - define('Order', ['jquery'], - function($) { - return Order; - }); -} + + var Order = function Order() { + var self = this; + + /** + * 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; - - /** - * 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; + + /** + * @return {Integer} + **/ + self.getId = function() { + return self.id; + } + + /** + * @param {Integer} id + **/ + self.setId = function (id) { + self.id = id; } - 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; - - self.complete = data.complete; + /** + * @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 (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; -} +})); diff --git a/samples/client/petstore/javascript/src/model/Pet.js b/samples/client/petstore/javascript/src/model/Pet.js index 25ae2e951c8..21de3265076 100644 --- a/samples/client/petstore/javascript/src/model/Pet.js +++ b/samples/client/petstore/javascript/src/model/Pet.js @@ -1,13 +1,22 @@ -// require files in Node.js environment -var Category;var Tag; -if (typeof module === 'object' && module.exports) { +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // 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 if ( typeof define === "function" && define.amd ) { define('StatusEnum', ['jquery'], function($) { @@ -37,164 +46,161 @@ var StatusEnum = function StatusEnum() { } -//export module -if ( typeof define === "function" && define.amd ) { - define('Pet', ['jquery', 'Category', 'Array'], - function($, Category, Array) { - return Pet; - }); -} + + var Pet = function Pet(photoUrls, name) { + var self = this; + + /** + * 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; - - /** - * 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; + + /** + * @return {Integer} + **/ + self.getId = function() { + return self.id; + } + + /** + * @param {Integer} id + **/ + self.setId = function (id) { + self.id = id; } - 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(); - - self.status = data.status; + /** + * 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 (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; -} +})); diff --git a/samples/client/petstore/javascript/src/model/Tag.js b/samples/client/petstore/javascript/src/model/Tag.js index 0fa97bd8c78..2dbf932f300 100644 --- a/samples/client/petstore/javascript/src/model/Tag.js +++ b/samples/client/petstore/javascript/src/model/Tag.js @@ -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; - - self.name = data.name; + /** + * @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 (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; -} +})); diff --git a/samples/client/petstore/javascript/src/model/User.js b/samples/client/petstore/javascript/src/model/User.js index 632208a523c..a76ccf19013 100644 --- a/samples/client/petstore/javascript/src/model/User.js +++ b/samples/client/petstore/javascript/src/model/User.js @@ -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 ) { - define('User', ['jquery'], - function($) { - return User; - }); -} - - -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; + /** + * @param {Integer} id + **/ + self.setId = function (id) { + self.id = id; } - 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; - - self.userStatus = data.userStatus; + /** + * 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 (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; -} +})); diff --git a/samples/client/petstore/javascript/test/ApiClientTest.js b/samples/client/petstore/javascript/test/ApiClientTest.js new file mode 100644 index 00000000000..f577a3ec7b6 --- /dev/null +++ b/samples/client/petstore/javascript/test/ApiClientTest.js @@ -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); + }); + }); +}); diff --git a/samples/client/petstore/javascript/test/api/PetApiTest.js b/samples/client/petstore/javascript/test/api/PetApiTest.js index 325cc16b616..f2c72bb8011 100644 --- a/samples/client/petstore/javascript/test/api/PetApiTest.js +++ b/samples/client/petstore/javascript/test/api/PetApiTest.js @@ -1,25 +1,21 @@ if (typeof module === 'object' && module.exports) { var expect = require('expect.js'); - var requireApiWithMocks = require('../helper.js').requireApiWithMocks; - var PetApi = requireApiWithMocks('PetApi'); - var Pet = require('../../src/model/Pet'); - var Category = require('../../src/model/Category'); - var Tag = require('../../src/model/Tag'); + var SwaggerPetstore = require('../../src/index'); } var api; beforeEach(function() { - api = new PetApi(); + api = new SwaggerPetstore.PetApi(); }); var createRandomPet = function() { var id = new Date().getTime(); - var pet = new Pet(); + var pet = new SwaggerPetstore.Pet(); pet.setId(id); pet.setName("gorilla" + id); - var category = new Category(); + var category = new SwaggerPetstore.Category(); category.setName("really-happy"); pet.setCategory(category); @@ -31,13 +27,17 @@ var createRandomPet = function() { }; describe('PetApi', function() { - it('should create and get pet', function (done) { + it('should create and get pet', function(done) { var pet = createRandomPet(); - api.addPet(pet).then(function() { - api.getPetById(pet.id, function(fetched, textStatus, jqXHR, error) { - if (error) throw error; + api.addPet(pet, function(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.id).to.be(pet.id); expect(fetched.getCategory()).to.be.ok(); @@ -46,8 +46,6 @@ describe('PetApi', function() { api.deletePet(pet.id); done(); }); - }, function(jqXHR, textStatus, errorThrown) { - throw errorThrown || textStatus; }); }); }); diff --git a/samples/client/petstore/javascript/test/helper.js b/samples/client/petstore/javascript/test/helper.js deleted file mode 100644 index 018b6428af6..00000000000 --- a/samples/client/petstore/javascript/test/helper.js +++ /dev/null @@ -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; diff --git a/samples/client/petstore/javascript/test/run_tests.html b/samples/client/petstore/javascript/test/run_tests.html index c5655275cc5..58118d8d7d4 100644 --- a/samples/client/petstore/javascript/test/run_tests.html +++ b/samples/client/petstore/javascript/test/run_tests.html @@ -10,7 +10,6 @@ - + + + + + + + +