From 7e9a5f00b1acdfa7295cc2d4eac890c2714029e5 Mon Sep 17 00:00:00 2001 From: delenius Date: Mon, 8 Feb 2016 12:31:00 -0800 Subject: [PATCH 1/6] Add usePromise parameter to JS client --- .../languages/JavascriptClientCodegen.java | 14 +++++++++++--- .../main/resources/Javascript/ApiClient.mustache | 15 +++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) 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 2a60c7fc1f0c..08f03e48b1bb 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 @@ -39,6 +39,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo private static final String PROJECT_DESCRIPTION = "projectDescription"; private static final String PROJECT_VERSION = "projectVersion"; private static final String PROJECT_LICENSE_NAME = "projectLicenseName"; + private static final String USE_PROMISES = "usePromises"; protected String projectName; protected String moduleName; @@ -47,7 +48,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo protected String sourceFolder = "src"; protected String localVariablePrefix = ""; - + protected boolean usePromises = false; + public JavascriptClientCodegen() { super(); outputFolder = "generated-code/js"; @@ -56,7 +58,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo templateDir = "Javascript"; apiPackage = "api"; modelPackage = "model"; - + // reference: http://www.w3schools.com/js/js_reserved.asp reservedWords = new HashSet( Arrays.asList( @@ -96,6 +98,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo "version of the project (Default: using info.version or \"1.0.0\")")); cliOptions.add(new CliOption(PROJECT_LICENSE_NAME, "name of the license the project uses (Default: using info.license.name)")); + cliOptions.add(new CliOption(USE_PROMISES, + "use Promises as return values from the client API, instead of superagent callbacks (Default: false)")); } @Override @@ -161,7 +165,10 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { sourceFolder = (String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER); } - + if (additionalProperties.containsKey(USE_PROMISES)) { + usePromises = Boolean.parseBoolean((String)additionalProperties.get(USE_PROMISES)); + } + if (swagger.getInfo() != null) { Info info = swagger.getInfo(); if (StringUtils.isBlank(projectName) && info.getTitle() != null) { @@ -204,6 +211,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo additionalProperties.put(PROJECT_VERSION, projectVersion); additionalProperties.put(CodegenConstants.LOCAL_VARIABLE_PREFIX, localVariablePrefix); additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder); + additionalProperties.put(USE_PROMISES, usePromises); supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js")); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache index b301da5c3012..55a786514851 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache @@ -214,6 +214,20 @@ request.accept(accept); } + {{#usePromises}} + return new Promise( function(resolve,reject) { + request.end(function(error, response) { + if (error) { + reject(error); + } + else { + var data = _this.deserialize(response, returnType); + resolve(data); + } + }); + }); + {{/usePromises}} + {{^usePromises}} request.end(function(error, response) { if (callback) { var data = null; @@ -225,6 +239,7 @@ }); return request; + {{/usePromises}} }; ApiClient.parseDate = function parseDate(str) { From e825b953f72ca8341e25c3f54dc86b8378608201 Mon Sep 17 00:00:00 2001 From: delenius Date: Mon, 8 Feb 2016 12:31:00 -0800 Subject: [PATCH 2/6] Add usePromise parameter to JS client --- .../languages/JavascriptClientCodegen.java | 14 +++++++++++--- .../main/resources/Javascript/ApiClient.mustache | 15 +++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) 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 cc5dcff3fa26..20c7fc62e6bc 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 @@ -23,6 +23,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo private static final String PROJECT_DESCRIPTION = "projectDescription"; private static final String PROJECT_VERSION = "projectVersion"; private static final String PROJECT_LICENSE_NAME = "projectLicenseName"; + private static final String USE_PROMISES = "usePromises"; protected String projectName; protected String moduleName; @@ -31,7 +32,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo protected String sourceFolder = "src"; protected String localVariablePrefix = ""; - + protected boolean usePromises = false; + public JavascriptClientCodegen() { super(); outputFolder = "generated-code/js"; @@ -40,7 +42,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo templateDir = "Javascript"; apiPackage = "api"; modelPackage = "model"; - + // reference: http://www.w3schools.com/js/js_reserved.asp reservedWords = new HashSet( Arrays.asList( @@ -80,6 +82,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo "version of the project (Default: using info.version or \"1.0.0\")")); cliOptions.add(new CliOption(PROJECT_LICENSE_NAME, "name of the license the project uses (Default: using info.license.name)")); + cliOptions.add(new CliOption(USE_PROMISES, + "use Promises as return values from the client API, instead of superagent callbacks (Default: false)")); } @Override @@ -146,7 +150,10 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { sourceFolder = (String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER); } - + if (additionalProperties.containsKey(USE_PROMISES)) { + usePromises = Boolean.parseBoolean((String)additionalProperties.get(USE_PROMISES)); + } + if (swagger.getInfo() != null) { Info info = swagger.getInfo(); if (StringUtils.isBlank(projectName) && info.getTitle() != null) { @@ -189,6 +196,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo additionalProperties.put(PROJECT_VERSION, projectVersion); additionalProperties.put(CodegenConstants.LOCAL_VARIABLE_PREFIX, localVariablePrefix); additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder); + additionalProperties.put(USE_PROMISES, usePromises); supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js")); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache index b301da5c3012..55a786514851 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache @@ -214,6 +214,20 @@ request.accept(accept); } + {{#usePromises}} + return new Promise( function(resolve,reject) { + request.end(function(error, response) { + if (error) { + reject(error); + } + else { + var data = _this.deserialize(response, returnType); + resolve(data); + } + }); + }); + {{/usePromises}} + {{^usePromises}} request.end(function(error, response) { if (callback) { var data = null; @@ -225,6 +239,7 @@ }); return request; + {{/usePromises}} }; ApiClient.parseDate = function parseDate(str) { From 73016186717f16ddf57e94c8b468c8f1512691b8 Mon Sep 17 00:00:00 2001 From: delenius Date: Mon, 8 Feb 2016 20:02:38 -0800 Subject: [PATCH 3/6] Add petstore tests for usePromises version --- bin/javascript-promise-petstore.sh | 34 ++ .../petstore/javascript-promise/.gitignore | 1 + .../petstore/javascript-promise/package.json | 17 + .../petstore/javascript-promise/pom.xml | 45 ++ .../javascript-promise/src/ApiClient.js | 291 +++++++++++++ .../javascript-promise/src/api/PetApi.js | 394 ++++++++++++++++++ .../javascript-promise/src/api/StoreApi.js | 170 ++++++++ .../javascript-promise/src/api/UserApi.js | 307 ++++++++++++++ .../petstore/javascript-promise/src/index.js | 23 + .../javascript-promise/src/model/Category.js | 89 ++++ .../javascript-promise/src/model/Order.js | 204 +++++++++ .../javascript-promise/src/model/Pet.js | 206 +++++++++ .../javascript-promise/src/model/Tag.js | 89 ++++ .../javascript-promise/src/model/User.js | 218 ++++++++++ .../javascript-promise/test/ApiClientTest.js | 155 +++++++ .../javascript-promise/test/api/PetApiTest.js | 186 +++++++++ .../javascript-promise/test/mocha.opts | 1 + .../javascript-promise/test/run_tests.html | 40 ++ 18 files changed, 2470 insertions(+) create mode 100755 bin/javascript-promise-petstore.sh create mode 100644 samples/client/petstore/javascript-promise/.gitignore create mode 100644 samples/client/petstore/javascript-promise/package.json create mode 100644 samples/client/petstore/javascript-promise/pom.xml create mode 100644 samples/client/petstore/javascript-promise/src/ApiClient.js create mode 100644 samples/client/petstore/javascript-promise/src/api/PetApi.js create mode 100644 samples/client/petstore/javascript-promise/src/api/StoreApi.js create mode 100644 samples/client/petstore/javascript-promise/src/api/UserApi.js create mode 100644 samples/client/petstore/javascript-promise/src/index.js create mode 100644 samples/client/petstore/javascript-promise/src/model/Category.js create mode 100644 samples/client/petstore/javascript-promise/src/model/Order.js create mode 100644 samples/client/petstore/javascript-promise/src/model/Pet.js create mode 100644 samples/client/petstore/javascript-promise/src/model/Tag.js create mode 100644 samples/client/petstore/javascript-promise/src/model/User.js create mode 100644 samples/client/petstore/javascript-promise/test/ApiClientTest.js create mode 100644 samples/client/petstore/javascript-promise/test/api/PetApiTest.js create mode 100644 samples/client/petstore/javascript-promise/test/mocha.opts create mode 100644 samples/client/petstore/javascript-promise/test/run_tests.html diff --git a/bin/javascript-promise-petstore.sh b/bin/javascript-promise-petstore.sh new file mode 100755 index 000000000000..e82fef3039db --- /dev/null +++ b/bin/javascript-promise-petstore.sh @@ -0,0 +1,34 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/javascript \ +-i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l javascript \ +-o samples/client/petstore/javascript-promise \ +--additional-properties usePromises=true" + +java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags diff --git a/samples/client/petstore/javascript-promise/.gitignore b/samples/client/petstore/javascript-promise/.gitignore new file mode 100644 index 000000000000..2ccbe4656c60 --- /dev/null +++ b/samples/client/petstore/javascript-promise/.gitignore @@ -0,0 +1 @@ +/node_modules/ diff --git a/samples/client/petstore/javascript-promise/package.json b/samples/client/petstore/javascript-promise/package.json new file mode 100644 index 000000000000..1fdf78cf2171 --- /dev/null +++ b/samples/client/petstore/javascript-promise/package.json @@ -0,0 +1,17 @@ +{ + "name": "swagger-petstore", + "version": "1.0.0", + "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", + "license": "Apache 2.0", + "main": "src/index.js", + "scripts": { + "test": "./node_modules/mocha/bin/mocha --recursive" + }, + "dependencies": { + "superagent": "1.7.1" + }, + "devDependencies": { + "mocha": "~2.3.4", + "expect.js": "~0.3.1" + } +} diff --git a/samples/client/petstore/javascript-promise/pom.xml b/samples/client/petstore/javascript-promise/pom.xml new file mode 100644 index 000000000000..d77a24fcd75c --- /dev/null +++ b/samples/client/petstore/javascript-promise/pom.xml @@ -0,0 +1,45 @@ + + 4.0.0 + io.swagger + swagger-petstore-javascript-promise + pom + 1.0-SNAPSHOT + Swagger Petstore - Javascript Client (Promise version) + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + npm-install + pre-integration-test + + exec + + + npm + + install + + + + + mocha + integration-test + + exec + + + npm + + test + + + + + + + + diff --git a/samples/client/petstore/javascript-promise/src/ApiClient.js b/samples/client/petstore/javascript-promise/src/ApiClient.js new file mode 100644 index 000000000000..0a3ec7305490 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/ApiClient.js @@ -0,0 +1,291 @@ +(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() { + /** + * The base path to put in front of every API call's (relative) path. + */ + this.basePath = 'http://petstore.swagger.io/v2'.replace(/\/+$/, ''); + + /** + * The default HTTP headers to be included for all API calls. + */ + this.defaultHeaders = {}; + }; + + ApiClient.prototype.paramToString = function paramToString(param) { + if (param == null) { + // return empty string for null and undefined + return ''; + } else if (param instanceof Date) { + return param.toJSON(); + } 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]; + }; + + /** + * Check if the given parameter value is like file content. + */ + ApiClient.prototype.isFileParam = function isFileParam(param) { + // fs.ReadStream in Node.js (but not in runtime like browserify) + if (typeof window === 'undefined' && + typeof require === 'function' && + require('fs') && + param instanceof require('fs').ReadStream) { + return true; + } + // Buffer in Node.js + if (typeof Buffer === 'function' && param instanceof Buffer) { + return true; + } + // Blob in browser + if (typeof Blob === 'function' && param instanceof Blob) { + return true; + } + // File in browser (it seems File object is also instance of Blob, but keep this for safe) + if (typeof File === 'function' && param instanceof File) { + return true; + } + return false; + }; + + /** + * 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 (this.isFileParam(value) || Array.isArray(value)) { + newParams[key] = value; + } else { + newParams[key] = this.paramToString(value); + } + } + } + return newParams; + }; + + /** + * Build parameter value according to the given collection format. + * @param {String} collectionFormat one of 'csv', 'ssv', 'tsv', 'pipes' and 'multi' + */ + ApiClient.prototype.buildCollectionParam = function buildCollectionParam(param, collectionFormat) { + if (param == null) { + return null; + } + switch (collectionFormat) { + case 'csv': + return param.map(this.paramToString).join(','); + case 'ssv': + return param.map(this.paramToString).join(' '); + case 'tsv': + return param.map(this.paramToString).join('\t'); + case 'pipes': + return param.map(this.paramToString).join('|'); + case 'multi': + // return the array directly as Superagent will handle it as expected + return param.map(this.paramToString); + default: + throw new Error('Unknown collection format: ' + collectionFormat); + } + }; + + ApiClient.prototype.deserialize = function deserialize(response, returnType) { + if (response == null || returnType == null) { + return null; + } + // Rely on Superagent for parsing response body. + // See http://visionmedia.github.io/superagent/#parsing-response-bodies + var data = response.body; + if (data == null) { + return null; + } + return ApiClient.convertToType(data, returnType); + }; + + ApiClient.prototype.callApi = function callApi(path, httpMethod, pathParams, + queryParams, headerParams, formParams, bodyParam, contentTypes, accepts, + returnType, callback) { + var _this = this; + 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.defaultHeaders).set(this.normalizeParams(headerParams)); + + var contentType = this.jsonPreferredMime(contentTypes); + if (contentType) { + request.type(contentType); + } else if (!request.header['Content-Type']) { + request.type('application/json'); + } + + 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 (this.isFileParam(_formParams[key])) { + // file field + request.attach(key, _formParams[key]); + } else { + request.field(key, _formParams[key]); + } + } + } + } else if (bodyParam) { + request.send(bodyParam); + } + + var accept = this.jsonPreferredMime(accepts); + if (accept) { + request.accept(accept); + } + + + return new Promise( function(resolve,reject) { + request.end(function(error, response) { + if (error) { + reject(error); + } + else { + var data = _this.deserialize(response, returnType); + resolve(data); + } + }); + }); + + + }; + + ApiClient.parseDate = function parseDate(str) { + str = str.replace(/T/i, ' '); + return new Date(str); + }; + + ApiClient.convertToType = function convertToType(data, type) { + switch (type) { + case 'Boolean': + return Boolean(data); + case 'Integer': + return parseInt(data, 10); + case 'Number': + return parseFloat(data); + case 'String': + return String(data); + case 'Date': + return this.parseDate(String(data)); + default: + if (typeof type === 'function') { + // for model type like: User + var model = new type(); + model.constructFromObject(data); + return model; + } else if (Array.isArray(type)) { + // for array type like: ['String'] + var itemType = type[0]; + return data.map(function(item) { + return ApiClient.convertToType(item, itemType); + }); + } else if (typeof type === 'object') { + // for plain object type like: {'String': 'Integer'} + var keyType, valueType; + for (var k in type) { + if (type.hasOwnProperty(k)) { + keyType = k; + valueType = type[k]; + break; + } + } + var result = {}; + for (var k in data) { + if (data.hasOwnProperty(k)) { + var key = ApiClient.convertToType(k, keyType); + var value = ApiClient.convertToType(data[k], valueType); + result[key] = value; + } + } + return result; + } else { + // for unknown type, return the data directly + return data; + } + } + }; + + ApiClient.default = new ApiClient(); + + return ApiClient; +})); diff --git a/samples/client/petstore/javascript-promise/src/api/PetApi.js b/samples/client/petstore/javascript-promise/src/api/PetApi.js new file mode 100644 index 000000000000..91e330eab92f --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/api/PetApi.js @@ -0,0 +1,394 @@ +(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'), require('../model/Pet')); + } 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'; + + var PetApi = function PetApi(apiClient) { + this.apiClient = apiClient || ApiClient.default; + + 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, 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 returnType = null; + + return this.apiClient.callApi( + '/pet', 'PUT', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * 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; + + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = ['application/json', 'application/xml']; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/pet', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param {[String]} 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: [Pet] + */ + self.findPetsByStatus = function(status, callback) { + var postBody = null; + + + + var pathParams = { + }; + var queryParams = { + 'status': this.buildCollectionParam(status, 'multi') + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = [Pet]; + + return this.apiClient.callApi( + '/pet/findByStatus', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param {[String]} tags Tags to filter by + * @param {function} callback the callback function, accepting three arguments: error, data, response + * data is of type: [Pet] + */ + self.findPetsByTags = function(tags, callback) { + var postBody = null; + + + + var pathParams = { + }; + var queryParams = { + 'tags': this.buildCollectionParam(tags, 'multi') + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = [Pet]; + + return this.apiClient.callApi( + '/pet/findByTags', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * 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; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw "Missing the required parameter 'petId' when calling getPetById"; + } + + + + var pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = Pet; + + return this.apiClient.callApi( + '/pet/{petId}', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * 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; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw "Missing the required parameter 'petId' when calling updatePetWithForm"; + } + + + + 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 returnType = null; + + return this.apiClient.callApi( + '/pet/{petId}', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * 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; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw "Missing the required parameter 'petId' when calling deletePet"; + } + + + + var pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + 'api_key': apiKey + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/pet/{petId}', 'DELETE', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * 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; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw "Missing the required parameter 'petId' when calling uploadFile"; + } + + + + 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 returnType = null; + + return this.apiClient.callApi( + '/pet/{petId}/uploadImage', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * 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: 'String' + */ + self.getPetByIdWithByteArray = function(petId, callback) { + var postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw "Missing the required parameter 'petId' when calling getPetByIdWithByteArray"; + } + + + + var pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = 'String'; + + return this.apiClient.callApi( + '/pet/{petId}?testing_byte_array=true', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param {String} 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 returnType = null; + + return this.apiClient.callApi( + '/pet?testing_byte_array=true', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + + }; + + return PetApi; +})); diff --git a/samples/client/petstore/javascript-promise/src/api/StoreApi.js b/samples/client/petstore/javascript-promise/src/api/StoreApi.js new file mode 100644 index 000000000000..632d5b836314 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/api/StoreApi.js @@ -0,0 +1,170 @@ +(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'), require('../model/Order')); + } 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'; + + var StoreApi = function StoreApi(apiClient) { + this.apiClient = apiClient || ApiClient.default; + + var self = this; + + + /** + * 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: {'String': 'Integer'} + */ + self.getInventory = function(callback) { + var postBody = null; + + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = {'String': 'Integer'}; + + return this.apiClient.callApi( + '/store/inventory', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * 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 pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = Order; + + return this.apiClient.callApi( + '/store/order', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * 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; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw "Missing the required parameter 'orderId' when calling getOrderById"; + } + + + + var pathParams = { + 'orderId': orderId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = Order; + + return this.apiClient.callApi( + '/store/order/{orderId}', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * 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; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw "Missing the required parameter 'orderId' when calling deleteOrder"; + } + + + + var pathParams = { + 'orderId': orderId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/store/order/{orderId}', 'DELETE', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + + }; + + return StoreApi; +})); diff --git a/samples/client/petstore/javascript-promise/src/api/UserApi.js b/samples/client/petstore/javascript-promise/src/api/UserApi.js new file mode 100644 index 000000000000..2ab1f1f3abb7 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/api/UserApi.js @@ -0,0 +1,307 @@ +(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'), require('../model/User')); + } 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'; + + var UserApi = function UserApi(apiClient) { + this.apiClient = apiClient || ApiClient.default; + + 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, 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 returnType = null; + + return this.apiClient.callApi( + '/user', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * Creates list of users with given input array + * + * @param {[User]} 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; + + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/user/createWithArray', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * Creates list of users with given input array + * + * @param {[User]} 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; + + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/user/createWithList', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * 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; + + + + var pathParams = { + }; + var queryParams = { + 'username': username, + 'password': password + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = 'String'; + + return this.apiClient.callApi( + '/user/login', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * 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 pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/user/logout', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * 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; + + // verify the required parameter 'username' is set + if (username == null) { + throw "Missing the required parameter 'username' when calling getUserByName"; + } + + + + var pathParams = { + 'username': username + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = User; + + return this.apiClient.callApi( + '/user/{username}', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * 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; + + // verify the required parameter 'username' is set + if (username == null) { + throw "Missing the required parameter 'username' when calling updateUser"; + } + + + + var pathParams = { + 'username': username + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/user/{username}', 'PUT', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + /** + * 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; + + // verify the required parameter 'username' is set + if (username == null) { + throw "Missing the required parameter 'username' when calling deleteUser"; + } + + + + var pathParams = { + 'username': username + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/user/{username}', 'DELETE', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, returnType, callback + ); + + } + + + }; + + return UserApi; +})); diff --git a/samples/client/petstore/javascript-promise/src/index.js b/samples/client/petstore/javascript-promise/src/index.js new file mode 100644 index 000000000000..a6b290f5e63a --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/index.js @@ -0,0 +1,23 @@ +(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'), require('./model/User'), require('./model/Category'), require('./model/Pet'), require('./model/Tag'), require('./model/Order'), require('./api/UserApi'), require('./api/StoreApi'), require('./api/PetApi')); + } +}(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-promise/src/model/Category.js b/samples/client/petstore/javascript-promise/src/model/Category.js new file mode 100644 index 000000000000..4b58f1e7c4d8 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/Category.js @@ -0,0 +1,89 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([undefined, '../ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(undefined, require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient); + } +}(this, function(module, ApiClient) { + 'use strict'; + + + + + + var Category = function Category() { + + /** + * datatype: Integer + **/ + this['id'] = null; + + /** + * datatype: String + **/ + this['name'] = null; + + }; + + Category.prototype.constructFromObject = function(data) { + if (!data) { + return this; + } + + this['id'] = ApiClient.convertToType(data['id'], 'Integer'); + + this['name'] = ApiClient.convertToType(data['name'], 'String'); + + return this; + } + + + /** + * @return {Integer} + **/ + Category.prototype.getId = function() { + return this['id']; + } + + /** + * @param {Integer} id + **/ + Category.prototype.setId = function(id) { + this['id'] = id; + } + + /** + * @return {String} + **/ + Category.prototype.getName = function() { + return this['name']; + } + + /** + * @param {String} name + **/ + Category.prototype.setName = function(name) { + this['name'] = name; + } + + + Category.prototype.toJson = function() { + return JSON.stringify(this); + } + + if (module) { + module.Category = Category; + } + + return Category; + + +})); diff --git a/samples/client/petstore/javascript-promise/src/model/Order.js b/samples/client/petstore/javascript-promise/src/model/Order.js new file mode 100644 index 000000000000..c9dd8403a4fb --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/Order.js @@ -0,0 +1,204 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([undefined, '../ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(undefined, require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient); + } +}(this, function(module, ApiClient) { + 'use strict'; + + + +//export module +if ( typeof define === "function" && define.amd ) { + define('StatusEnum', [], function() { + return StatusEnum; + }); +} + +var StatusEnum = function StatusEnum() { + var self = this; + + + /** + * @const + */ + self.PLACED = "placed", + + /** + * @const + */ + self.APPROVED = "approved", + + /** + * @const + */ + self.DELIVERED = "delivered"; + +} + + + + var Order = function Order() { + + /** + * datatype: Integer + **/ + this['id'] = null; + + /** + * datatype: Integer + **/ + this['petId'] = null; + + /** + * datatype: Integer + **/ + this['quantity'] = null; + + /** + * datatype: Date + **/ + this['shipDate'] = null; + + /** + * Order Status + * datatype: StatusEnum + **/ + this['status'] = null; + + /** + * datatype: Boolean + **/ + this['complete'] = null; + + }; + + Order.prototype.constructFromObject = function(data) { + if (!data) { + return this; + } + + this['id'] = ApiClient.convertToType(data['id'], 'Integer'); + + this['petId'] = ApiClient.convertToType(data['petId'], 'Integer'); + + this['quantity'] = ApiClient.convertToType(data['quantity'], 'Integer'); + + this['shipDate'] = ApiClient.convertToType(data['shipDate'], 'Date'); + + this['status'] = ApiClient.convertToType(data['status'], 'String'); + + this['complete'] = ApiClient.convertToType(data['complete'], 'Boolean'); + + return this; + } + + + /** + * @return {Integer} + **/ + Order.prototype.getId = function() { + return this['id']; + } + + /** + * @param {Integer} id + **/ + Order.prototype.setId = function(id) { + this['id'] = id; + } + + /** + * @return {Integer} + **/ + Order.prototype.getPetId = function() { + return this['petId']; + } + + /** + * @param {Integer} petId + **/ + Order.prototype.setPetId = function(petId) { + this['petId'] = petId; + } + + /** + * @return {Integer} + **/ + Order.prototype.getQuantity = function() { + return this['quantity']; + } + + /** + * @param {Integer} quantity + **/ + Order.prototype.setQuantity = function(quantity) { + this['quantity'] = quantity; + } + + /** + * @return {Date} + **/ + Order.prototype.getShipDate = function() { + return this['shipDate']; + } + + /** + * @param {Date} shipDate + **/ + Order.prototype.setShipDate = function(shipDate) { + this['shipDate'] = shipDate; + } + + /** + * get Order Status + * @return {StatusEnum} + **/ + Order.prototype.getStatus = function() { + return this['status']; + } + + /** + * set Order Status + * @param {StatusEnum} status + **/ + Order.prototype.setStatus = function(status) { + this['status'] = status; + } + + /** + * @return {Boolean} + **/ + Order.prototype.getComplete = function() { + return this['complete']; + } + + /** + * @param {Boolean} complete + **/ + Order.prototype.setComplete = function(complete) { + this['complete'] = complete; + } + + + Order.prototype.toJson = function() { + return JSON.stringify(this); + } + + if (module) { + module.Order = Order; + } + + return Order; + + +})); diff --git a/samples/client/petstore/javascript-promise/src/model/Pet.js b/samples/client/petstore/javascript-promise/src/model/Pet.js new file mode 100644 index 000000000000..60b24a3f8e53 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/Pet.js @@ -0,0 +1,206 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([undefined, '../ApiClient', './Category', './Tag'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(undefined, require('../ApiClient'), require('./Category'), require('./Tag')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Category, root.SwaggerPetstore.Tag); + } +}(this, function(module, ApiClient, Category, Tag) { + 'use strict'; + + + +//export module +if ( typeof define === "function" && define.amd ) { + define('StatusEnum', [], function() { + return StatusEnum; + }); +} + +var StatusEnum = function StatusEnum() { + var self = this; + + + /** + * @const + */ + self.AVAILABLE = "available", + + /** + * @const + */ + self.PENDING = "pending", + + /** + * @const + */ + self.SOLD = "sold"; + +} + + + + var Pet = function Pet(photoUrls, name) { + + /** + * datatype: Integer + **/ + this['id'] = null; + + /** + * datatype: Category + **/ + this['category'] = new Category(); + + /** + * datatype: String + * required + **/ + this['name'] = name; + + /** + * datatype: [String] + * required + **/ + this['photoUrls'] = photoUrls; + + /** + * datatype: [Tag] + **/ + this['tags'] = []; + + /** + * pet status in the store + * datatype: StatusEnum + **/ + this['status'] = null; + + }; + + Pet.prototype.constructFromObject = function(data) { + if (!data) { + return this; + } + + this['id'] = ApiClient.convertToType(data['id'], 'Integer'); + + this['category'].constructFromObject(data['category']); + + this['name'] = ApiClient.convertToType(data['name'], 'String'); + + this['photoUrls'] = ApiClient.convertToType(data['photoUrls'], ['String']); + + this['tags'] = ApiClient.convertToType(data['tags'], [Tag]); + + this['status'] = ApiClient.convertToType(data['status'], 'String'); + + return this; + } + + + /** + * @return {Integer} + **/ + Pet.prototype.getId = function() { + return this['id']; + } + + /** + * @param {Integer} id + **/ + Pet.prototype.setId = function(id) { + this['id'] = id; + } + + /** + * @return {Category} + **/ + Pet.prototype.getCategory = function() { + return this['category']; + } + + /** + * @param {Category} category + **/ + Pet.prototype.setCategory = function(category) { + this['category'] = category; + } + + /** + * @return {String} + **/ + Pet.prototype.getName = function() { + return this['name']; + } + + /** + * @param {String} name + **/ + Pet.prototype.setName = function(name) { + this['name'] = name; + } + + /** + * @return {[String]} + **/ + Pet.prototype.getPhotoUrls = function() { + return this['photoUrls']; + } + + /** + * @param {[String]} photoUrls + **/ + Pet.prototype.setPhotoUrls = function(photoUrls) { + this['photoUrls'] = photoUrls; + } + + /** + * @return {[Tag]} + **/ + Pet.prototype.getTags = function() { + return this['tags']; + } + + /** + * @param {[Tag]} tags + **/ + Pet.prototype.setTags = function(tags) { + this['tags'] = tags; + } + + /** + * get pet status in the store + * @return {StatusEnum} + **/ + Pet.prototype.getStatus = function() { + return this['status']; + } + + /** + * set pet status in the store + * @param {StatusEnum} status + **/ + Pet.prototype.setStatus = function(status) { + this['status'] = status; + } + + + Pet.prototype.toJson = function() { + return JSON.stringify(this); + } + + if (module) { + module.Pet = Pet; + } + + return Pet; + + +})); diff --git a/samples/client/petstore/javascript-promise/src/model/Tag.js b/samples/client/petstore/javascript-promise/src/model/Tag.js new file mode 100644 index 000000000000..ac3d53734915 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/Tag.js @@ -0,0 +1,89 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([undefined, '../ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(undefined, require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient); + } +}(this, function(module, ApiClient) { + 'use strict'; + + + + + + var Tag = function Tag() { + + /** + * datatype: Integer + **/ + this['id'] = null; + + /** + * datatype: String + **/ + this['name'] = null; + + }; + + Tag.prototype.constructFromObject = function(data) { + if (!data) { + return this; + } + + this['id'] = ApiClient.convertToType(data['id'], 'Integer'); + + this['name'] = ApiClient.convertToType(data['name'], 'String'); + + return this; + } + + + /** + * @return {Integer} + **/ + Tag.prototype.getId = function() { + return this['id']; + } + + /** + * @param {Integer} id + **/ + Tag.prototype.setId = function(id) { + this['id'] = id; + } + + /** + * @return {String} + **/ + Tag.prototype.getName = function() { + return this['name']; + } + + /** + * @param {String} name + **/ + Tag.prototype.setName = function(name) { + this['name'] = name; + } + + + Tag.prototype.toJson = function() { + return JSON.stringify(this); + } + + if (module) { + module.Tag = Tag; + } + + return Tag; + + +})); diff --git a/samples/client/petstore/javascript-promise/src/model/User.js b/samples/client/petstore/javascript-promise/src/model/User.js new file mode 100644 index 000000000000..2ee006e0ac96 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/User.js @@ -0,0 +1,218 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([undefined, '../ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(undefined, require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient); + } +}(this, function(module, ApiClient) { + 'use strict'; + + + + + + var User = function User() { + + /** + * datatype: Integer + **/ + this['id'] = null; + + /** + * datatype: String + **/ + this['username'] = null; + + /** + * datatype: String + **/ + this['firstName'] = null; + + /** + * datatype: String + **/ + this['lastName'] = null; + + /** + * datatype: String + **/ + this['email'] = null; + + /** + * datatype: String + **/ + this['password'] = null; + + /** + * datatype: String + **/ + this['phone'] = null; + + /** + * User Status + * datatype: Integer + **/ + this['userStatus'] = null; + + }; + + User.prototype.constructFromObject = function(data) { + if (!data) { + return this; + } + + this['id'] = ApiClient.convertToType(data['id'], 'Integer'); + + this['username'] = ApiClient.convertToType(data['username'], 'String'); + + this['firstName'] = ApiClient.convertToType(data['firstName'], 'String'); + + this['lastName'] = ApiClient.convertToType(data['lastName'], 'String'); + + this['email'] = ApiClient.convertToType(data['email'], 'String'); + + this['password'] = ApiClient.convertToType(data['password'], 'String'); + + this['phone'] = ApiClient.convertToType(data['phone'], 'String'); + + this['userStatus'] = ApiClient.convertToType(data['userStatus'], 'Integer'); + + return this; + } + + + /** + * @return {Integer} + **/ + User.prototype.getId = function() { + return this['id']; + } + + /** + * @param {Integer} id + **/ + User.prototype.setId = function(id) { + this['id'] = id; + } + + /** + * @return {String} + **/ + User.prototype.getUsername = function() { + return this['username']; + } + + /** + * @param {String} username + **/ + User.prototype.setUsername = function(username) { + this['username'] = username; + } + + /** + * @return {String} + **/ + User.prototype.getFirstName = function() { + return this['firstName']; + } + + /** + * @param {String} firstName + **/ + User.prototype.setFirstName = function(firstName) { + this['firstName'] = firstName; + } + + /** + * @return {String} + **/ + User.prototype.getLastName = function() { + return this['lastName']; + } + + /** + * @param {String} lastName + **/ + User.prototype.setLastName = function(lastName) { + this['lastName'] = lastName; + } + + /** + * @return {String} + **/ + User.prototype.getEmail = function() { + return this['email']; + } + + /** + * @param {String} email + **/ + User.prototype.setEmail = function(email) { + this['email'] = email; + } + + /** + * @return {String} + **/ + User.prototype.getPassword = function() { + return this['password']; + } + + /** + * @param {String} password + **/ + User.prototype.setPassword = function(password) { + this['password'] = password; + } + + /** + * @return {String} + **/ + User.prototype.getPhone = function() { + return this['phone']; + } + + /** + * @param {String} phone + **/ + User.prototype.setPhone = function(phone) { + this['phone'] = phone; + } + + /** + * get User Status + * @return {Integer} + **/ + User.prototype.getUserStatus = function() { + return this['userStatus']; + } + + /** + * set User Status + * @param {Integer} userStatus + **/ + User.prototype.setUserStatus = function(userStatus) { + this['userStatus'] = userStatus; + } + + + User.prototype.toJson = function() { + return JSON.stringify(this); + } + + if (module) { + module.User = User; + } + + return User; + + +})); diff --git a/samples/client/petstore/javascript-promise/test/ApiClientTest.js b/samples/client/petstore/javascript-promise/test/ApiClientTest.js new file mode 100644 index 000000000000..4b23a57e85b4 --- /dev/null +++ b/samples/client/petstore/javascript-promise/test/ApiClientTest.js @@ -0,0 +1,155 @@ +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('#buildCollectionParam', function() { + var param; + + beforeEach(function() { + param = ['aa', 'bb', 123]; + }); + + it('works for csv', function() { + expect(apiClient.buildCollectionParam(param, 'csv')).to.be('aa,bb,123'); + }); + + it('works for ssv', function() { + expect(apiClient.buildCollectionParam(param, 'ssv')).to.be('aa bb 123'); + }); + + it('works for tsv', function() { + expect(apiClient.buildCollectionParam(param, 'tsv')).to.be('aa\tbb\t123'); + }); + + it('works for pipes', function() { + expect(apiClient.buildCollectionParam(param, 'pipes')).to.be('aa|bb|123'); + }); + + it('works for multi', function() { + expect(apiClient.buildCollectionParam(param, 'multi')).to.eql(['aa', 'bb', '123']); + }); + + it('fails for invalid collection format', function() { + expect(function() { apiClient.buildCollectionParam(param, 'INVALID'); }).to.throwError(); + }); + }); + + 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); + }); + }); + + /* + describe('#defaultHeaders', function() { + it('should initialize default headers to be an empty object', function() { + expect(apiClient.defaultHeaders).to.eql({}); + }); + + it('should put default headers in request', function() { + var newClient = new SwaggerPetstore.ApiClient; + newClient.defaultHeaders['Content-Type'] = 'text/plain' + newClient.defaultHeaders['api_key'] = 'special-key' + + var expected = {'Content-Type': 'text/plain', 'api_key': 'special-key'}; + expect(newClient.defaultHeaders).to.eql(expected); + var req = makeDumbRequest(newClient); + req.unset('User-Agent'); + expect(req.header).to.eql(expected); + }); + + it('should override default headers with provided header params', function() { + var newClient = new SwaggerPetstore.ApiClient; + newClient.defaultHeaders['Content-Type'] = 'text/plain' + newClient.defaultHeaders['api_key'] = 'special-key' + + var headerParams = {'Content-Type': 'application/json', 'Authorization': 'Bearer test-token'} + var expected = { + 'Content-Type': 'application/json', + 'api_key': 'special-key', + 'Authorization': 'Bearer test-token' + }; + var req = makeDumbRequest(newClient, {headerParams: headerParams}); + req.unset('User-Agent'); + expect(req.header).to.eql(expected); + }); + }); +*/ + +}); + +function makeDumbRequest(apiClient, opts) { + opts = opts || {}; + var path = opts.path || '/store/inventory'; + var httpMethod = opts.httpMethod || 'GET'; + var pathParams = opts.pathParams || {}; + var queryParams = opts.queryParams || {}; + var headerParams = opts.headerParams || {}; + var formParams = opts.formParams || {}; + var bodyParam = opts.bodyParam; + var contentTypes = opts.contentTypes || []; + var accepts = opts.accepts || []; + var callback = opts.callback; + return apiClient.callApi(path, httpMethod, pathParams, queryParams, + headerParams, formParams, bodyParam, contentTypes, accepts, callback + ); +} diff --git a/samples/client/petstore/javascript-promise/test/api/PetApiTest.js b/samples/client/petstore/javascript-promise/test/api/PetApiTest.js new file mode 100644 index 000000000000..f57770999b81 --- /dev/null +++ b/samples/client/petstore/javascript-promise/test/api/PetApiTest.js @@ -0,0 +1,186 @@ +if (typeof module === 'object' && module.exports) { + var expect = require('expect.js'); + var SwaggerPetstore = require('../../src/index'); +} + +var api; + +beforeEach(function() { + api = new SwaggerPetstore.PetApi(); +}); + +var createRandomPet = function() { + var id = new Date().getTime(); + var pet = new SwaggerPetstore.Pet(); + pet.setId(id); + pet.setName("gorilla" + id); + + var category = new SwaggerPetstore.Category(); + category.setName("really-happy"); + pet.setCategory(category); + + pet.setStatus('available'); + var photos = ["http://foo.bar.com/1", "http://foo.bar.com/2"]; + pet.setPhotoUrls(photos); + + return pet; +}; + +describe('PetApi', function() { + it('should create and get pet', function(done) { + var pet = createRandomPet(); + api.addPet(pet) + .then(function() { + return api.getPetById(pet.id) + }) + .then(function(fetched) { + //expect(response.status).to.be(200); + //expect(response.ok).to.be(true); + //expect(response.get('Content-Type')).to.be('application/json'); + expect(fetched).to.be.ok(); + expect(fetched.id).to.be(pet.id); + expect(fetched.getPhotoUrls()).to.eql(pet.getPhotoUrls()); + expect(fetched.getCategory()).to.be.ok(); + expect(fetched.getCategory().getName()).to.be(pet.getCategory().getName()); + + api.deletePet(pet.id); + done(); + }); + }); +}); + +/* + @Test + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (ApiException e) { + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } +} +*/ diff --git a/samples/client/petstore/javascript-promise/test/mocha.opts b/samples/client/petstore/javascript-promise/test/mocha.opts new file mode 100644 index 000000000000..907011807d68 --- /dev/null +++ b/samples/client/petstore/javascript-promise/test/mocha.opts @@ -0,0 +1 @@ +--timeout 10000 diff --git a/samples/client/petstore/javascript-promise/test/run_tests.html b/samples/client/petstore/javascript-promise/test/run_tests.html new file mode 100644 index 000000000000..2916234bcf31 --- /dev/null +++ b/samples/client/petstore/javascript-promise/test/run_tests.html @@ -0,0 +1,40 @@ + + + + Mocha Tests + + + +
+ + + + + + + + + + + + + + + + + + + + + + + From aab96ec7722c7949e134997ccb20886ab21b9407 Mon Sep 17 00:00:00 2001 From: delenius Date: Mon, 8 Feb 2016 23:39:05 -0800 Subject: [PATCH 4/6] Remove unused callback param when using promises --- .../resources/Javascript/ApiClient.mustache | 2 +- .../main/resources/Javascript/api.mustache | 6 +- .../javascript-promise/src/ApiClient.js | 2 +- .../javascript-promise/src/api/PetApi.js | 60 +++++++++---------- .../javascript-promise/src/api/StoreApi.js | 24 ++++---- .../javascript-promise/src/api/UserApi.js | 48 +++++++-------- .../petstore/javascript/src/ApiClient.js | 3 + 7 files changed, 74 insertions(+), 71 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache index 55a786514851..38867a6f341b 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache @@ -173,7 +173,7 @@ ApiClient.prototype.callApi = function callApi(path, httpMethod, pathParams, queryParams, headerParams, formParams, bodyParam, contentTypes, accepts, - returnType, callback) { + returnType{{^usePromises}}, callback{{/usePromises}}) { var _this = this; var url = this.buildUrl(path, pathParams); var request = superagent(httpMethod, url); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache index 57c3192400f6..386cf9380eab 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache @@ -25,10 +25,10 @@ * {{summary}} * {{notes}} {{#allParams}} * @param {{=<% %>=}}{<% dataType %>} <%={{ }}=%> {{paramName}} {{description}} - {{/allParams}} * @param {function} callback the callback function, accepting three arguments: error, data, response{{#returnType}} + {{/allParams}} {{^usePromises}}* @param {function} callback the callback function, accepting three arguments: error, data, response{{/usePromises}}{{#returnType}} * data is of type: {{{returnType}}}{{/returnType}} */ - self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}callback) { + self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{^usePromises}}{{#hasParams}}, {{/hasParams}}callback{{/usePromises}}) { var postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set @@ -58,7 +58,7 @@ return this.apiClient.callApi( '<&path>', '', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType<^usePromises>, callback ); <={{ }}=> } diff --git a/samples/client/petstore/javascript-promise/src/ApiClient.js b/samples/client/petstore/javascript-promise/src/ApiClient.js index 0a3ec7305490..c6843ed75608 100644 --- a/samples/client/petstore/javascript-promise/src/ApiClient.js +++ b/samples/client/petstore/javascript-promise/src/ApiClient.js @@ -173,7 +173,7 @@ ApiClient.prototype.callApi = function callApi(path, httpMethod, pathParams, queryParams, headerParams, formParams, bodyParam, contentTypes, accepts, - returnType, callback) { + returnType) { var _this = this; var url = this.buildUrl(path, pathParams); var request = superagent(httpMethod, url); diff --git a/samples/client/petstore/javascript-promise/src/api/PetApi.js b/samples/client/petstore/javascript-promise/src/api/PetApi.js index 91e330eab92f..d2ece31da91d 100644 --- a/samples/client/petstore/javascript-promise/src/api/PetApi.js +++ b/samples/client/petstore/javascript-promise/src/api/PetApi.js @@ -25,9 +25,9 @@ * 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) { + self.updatePet = function(body) { var postBody = body; @@ -48,7 +48,7 @@ return this.apiClient.callApi( '/pet', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -57,9 +57,9 @@ * 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) { + self.addPet = function(body) { var postBody = body; @@ -80,7 +80,7 @@ return this.apiClient.callApi( '/pet', 'POST', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -89,10 +89,10 @@ * Finds Pets by status * Multiple status values can be provided with comma seperated strings * @param {[String]} 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: [Pet] */ - self.findPetsByStatus = function(status, callback) { + self.findPetsByStatus = function(status) { var postBody = null; @@ -114,7 +114,7 @@ return this.apiClient.callApi( '/pet/findByStatus', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -123,10 +123,10 @@ * Finds Pets by tags * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. * @param {[String]} tags Tags to filter by - * @param {function} callback the callback function, accepting three arguments: error, data, response + * data is of type: [Pet] */ - self.findPetsByTags = function(tags, callback) { + self.findPetsByTags = function(tags) { var postBody = null; @@ -148,7 +148,7 @@ return this.apiClient.callApi( '/pet/findByTags', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -157,10 +157,10 @@ * 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) { + self.getPetById = function(petId) { var postBody = null; // verify the required parameter 'petId' is set @@ -187,7 +187,7 @@ return this.apiClient.callApi( '/pet/{petId}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -198,9 +198,9 @@ * @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) { + self.updatePetWithForm = function(petId, name, status) { var postBody = null; // verify the required parameter 'petId' is set @@ -229,7 +229,7 @@ return this.apiClient.callApi( '/pet/{petId}', 'POST', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -239,9 +239,9 @@ * * @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) { + self.deletePet = function(petId, apiKey) { var postBody = null; // verify the required parameter 'petId' is set @@ -269,7 +269,7 @@ return this.apiClient.callApi( '/pet/{petId}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -280,9 +280,9 @@ * @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) { + self.uploadFile = function(petId, additionalMetadata, file) { var postBody = null; // verify the required parameter 'petId' is set @@ -311,7 +311,7 @@ return this.apiClient.callApi( '/pet/{petId}/uploadImage', 'POST', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -320,10 +320,10 @@ * 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: 'String' */ - self.getPetByIdWithByteArray = function(petId, callback) { + self.getPetByIdWithByteArray = function(petId) { var postBody = null; // verify the required parameter 'petId' is set @@ -350,7 +350,7 @@ return this.apiClient.callApi( '/pet/{petId}?testing_byte_array=true', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -359,9 +359,9 @@ * Fake endpoint to test byte array in body parameter for adding a new pet to the store * * @param {String} 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) { + self.addPetUsingByteArray = function(body) { var postBody = body; @@ -382,7 +382,7 @@ return this.apiClient.callApi( '/pet?testing_byte_array=true', 'POST', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } diff --git a/samples/client/petstore/javascript-promise/src/api/StoreApi.js b/samples/client/petstore/javascript-promise/src/api/StoreApi.js index 632d5b836314..d6f0503c1367 100644 --- a/samples/client/petstore/javascript-promise/src/api/StoreApi.js +++ b/samples/client/petstore/javascript-promise/src/api/StoreApi.js @@ -24,10 +24,10 @@ /** * 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: {'String': 'Integer'} */ - self.getInventory = function(callback) { + self.getInventory = function() { var postBody = null; @@ -48,7 +48,7 @@ return this.apiClient.callApi( '/store/inventory', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -57,10 +57,10 @@ * 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) { + self.placeOrder = function(body) { var postBody = body; @@ -81,7 +81,7 @@ return this.apiClient.callApi( '/store/order', 'POST', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -90,10 +90,10 @@ * 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) { + self.getOrderById = function(orderId) { var postBody = null; // verify the required parameter 'orderId' is set @@ -120,7 +120,7 @@ return this.apiClient.callApi( '/store/order/{orderId}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -129,9 +129,9 @@ * 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) { + self.deleteOrder = function(orderId) { var postBody = null; // verify the required parameter 'orderId' is set @@ -158,7 +158,7 @@ return this.apiClient.callApi( '/store/order/{orderId}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } diff --git a/samples/client/petstore/javascript-promise/src/api/UserApi.js b/samples/client/petstore/javascript-promise/src/api/UserApi.js index 2ab1f1f3abb7..09f7c9e0d5b4 100644 --- a/samples/client/petstore/javascript-promise/src/api/UserApi.js +++ b/samples/client/petstore/javascript-promise/src/api/UserApi.js @@ -25,9 +25,9 @@ * 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) { + self.createUser = function(body) { var postBody = body; @@ -48,7 +48,7 @@ return this.apiClient.callApi( '/user', 'POST', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -57,9 +57,9 @@ * Creates list of users with given input array * * @param {[User]} body List of user object - * @param {function} callback the callback function, accepting three arguments: error, data, response + */ - self.createUsersWithArrayInput = function(body, callback) { + self.createUsersWithArrayInput = function(body) { var postBody = body; @@ -80,7 +80,7 @@ return this.apiClient.callApi( '/user/createWithArray', 'POST', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -89,9 +89,9 @@ * Creates list of users with given input array * * @param {[User]} body List of user object - * @param {function} callback the callback function, accepting three arguments: error, data, response + */ - self.createUsersWithListInput = function(body, callback) { + self.createUsersWithListInput = function(body) { var postBody = body; @@ -112,7 +112,7 @@ return this.apiClient.callApi( '/user/createWithList', 'POST', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -122,10 +122,10 @@ * * @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) { + self.loginUser = function(username, password) { var postBody = null; @@ -148,7 +148,7 @@ return this.apiClient.callApi( '/user/login', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -156,9 +156,9 @@ /** * Logs out current logged in user session * - * @param {function} callback the callback function, accepting three arguments: error, data, response + */ - self.logoutUser = function(callback) { + self.logoutUser = function() { var postBody = null; @@ -179,7 +179,7 @@ return this.apiClient.callApi( '/user/logout', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -188,10 +188,10 @@ * 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) { + self.getUserByName = function(username) { var postBody = null; // verify the required parameter 'username' is set @@ -218,7 +218,7 @@ return this.apiClient.callApi( '/user/{username}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -228,9 +228,9 @@ * 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) { + self.updateUser = function(username, body) { var postBody = body; // verify the required parameter 'username' is set @@ -257,7 +257,7 @@ return this.apiClient.callApi( '/user/{username}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } @@ -266,9 +266,9 @@ * 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) { + self.deleteUser = function(username) { var postBody = null; // verify the required parameter 'username' is set @@ -295,7 +295,7 @@ return this.apiClient.callApi( '/user/{username}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, - contentTypes, accepts, returnType, callback + contentTypes, accepts, returnType ); } diff --git a/samples/client/petstore/javascript/src/ApiClient.js b/samples/client/petstore/javascript/src/ApiClient.js index 9968b2dfc884..a102b4fb0cb3 100644 --- a/samples/client/petstore/javascript/src/ApiClient.js +++ b/samples/client/petstore/javascript/src/ApiClient.js @@ -214,6 +214,8 @@ request.accept(accept); } + + request.end(function(error, response) { if (callback) { var data = null; @@ -225,6 +227,7 @@ }); return request; + }; ApiClient.parseDate = function parseDate(str) { From dd29cf9d53b4e100275e243b0c83d5c3ea3325e2 Mon Sep 17 00:00:00 2001 From: delenius Date: Tue, 9 Feb 2016 07:35:45 -0800 Subject: [PATCH 5/6] Use defaultValue for the usePromise CliOption --- .../io/swagger/codegen/languages/JavascriptClientCodegen.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 20c7fc62e6bc..5bde96b68b26 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 @@ -83,7 +83,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo cliOptions.add(new CliOption(PROJECT_LICENSE_NAME, "name of the license the project uses (Default: using info.license.name)")); cliOptions.add(new CliOption(USE_PROMISES, - "use Promises as return values from the client API, instead of superagent callbacks (Default: false)")); + "use Promises as return values from the client API, instead of superagent callbacks") + .defaultValue(Boolean.FALSE.toString())); } @Override From d56d626450cd9bd9d20c18aba5514fe934a0fd8a Mon Sep 17 00:00:00 2001 From: delenius Date: Tue, 9 Feb 2016 07:50:12 -0800 Subject: [PATCH 6/6] Remove wildcards from imports --- .../languages/JavascriptClientCodegen.java | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) 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 5bde96b68b26..2b848393e977 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 @@ -1,18 +1,38 @@ package io.swagger.codegen.languages; import com.google.common.base.Strings; -import io.swagger.codegen.*; -import io.swagger.models.*; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.SupportingFile; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.models.Info; +import io.swagger.models.License; +import io.swagger.models.Model; +import io.swagger.models.Operation; +import io.swagger.models.Swagger; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; import io.swagger.models.properties.RefProperty; + import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; public class JavascriptClientCodegen extends DefaultCodegen implements CodegenConfig { @SuppressWarnings("hiding")