Skip to content

Add usePromise parameter to JS client #2072

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Feb 9, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions bin/javascript-promise-petstore.sh
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,12 @@ public void flattenProperties(Map<String, Property> properties, String path) {
Map<String, Model> modelsToAdd = new HashMap<String, Model>();
for (String key : properties.keySet()) {
Property property = properties.get(key);
if (property instanceof ObjectProperty && ((ObjectProperty)property).getProperties().size() > 0) {
if(property instanceof ObjectProperty && ((ObjectProperty)property).getProperties() == null) {
MapProperty mp = new MapProperty();
mp.setAdditionalProperties(new StringProperty());
properties.put(key, mp);
}
else if (property instanceof ObjectProperty && ((ObjectProperty)property).getProperties().size() > 0) {
String modelName = uniqueName(path + "_" + key);

ObjectProperty op = (ObjectProperty) property;
Expand Down Expand Up @@ -276,7 +281,6 @@ public void flattenProperties(Map<String, Property> properties, String path) {
swagger.addDefinition(modelName, innerModel);
}
}
} else {
}
}
if (propsToUpdate.size() > 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,22 @@
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.*;
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.ArrayList;
import java.util.Arrays;
Expand All @@ -26,10 +34,6 @@
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JavascriptClientCodegen extends DefaultCodegen implements CodegenConfig {
@SuppressWarnings("hiding")
private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptClientCodegen.class);
Expand All @@ -39,6 +43,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;
Expand All @@ -47,7 +52,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";
Expand All @@ -56,7 +62,7 @@ public JavascriptClientCodegen() {
templateDir = "Javascript";
apiPackage = "api";
modelPackage = "model";

// reference: http://www.w3schools.com/js/js_reserved.asp
reservedWords = new HashSet<String>(
Arrays.asList(
Expand Down Expand Up @@ -96,6 +102,9 @@ public JavascriptClientCodegen() {
"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")
.defaultValue(Boolean.FALSE.toString()));
}

@Override
Expand Down Expand Up @@ -133,6 +142,7 @@ public void processOpts() {
typeMapping.put("double", "Number");
typeMapping.put("number", "Number");
typeMapping.put("DateTime", "Date");
typeMapping.put("Date", "Date");
// binary not supported in JavaScript client right now, using String as a workaround
typeMapping.put("binary", "String");

Expand Down Expand Up @@ -161,7 +171,10 @@ public void preprocessSwagger(Swagger swagger) {
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) {
Expand Down Expand Up @@ -204,6 +217,7 @@ public void preprocessSwagger(Swagger swagger) {
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"));
Expand Down Expand Up @@ -358,7 +372,7 @@ public String toOperationId(String operationId) {

// method name cannot use reserved keyword, e.g. return
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
operationId = escapeReservedWord(operationId);
}

return camelize(sanitizeName(operationId), true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand All @@ -225,6 +239,7 @@
});

return request;
{{/usePromises}}
};

ApiClient.parseDate = function parseDate(str) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -58,7 +58,7 @@
return this.apiClient.callApi(
'<&path>', '<httpMethod>',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, returnType, callback
contentTypes, accepts, returnType<^usePromises>, callback</usePromises>
);
<={{ }}=>
}
Expand Down
4 changes: 2 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
Expand Down
1 change: 1 addition & 0 deletions samples/client/petstore/javascript-promise/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/node_modules/
17 changes: 17 additions & 0 deletions samples/client/petstore/javascript-promise/package.json
Original file line number Diff line number Diff line change
@@ -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 <a href=\"http://swagger.io\">http://swagger.io</a> 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"
}
}
45 changes: 45 additions & 0 deletions samples/client/petstore/javascript-promise/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>io.swagger</groupId>
<artifactId>swagger-petstore-javascript-promise</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>Swagger Petstore - Javascript Client (Promise version)</name>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>npm-install</id>
<phase>pre-integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>mocha</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>test</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Loading