Skip to content
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

Update NodeJS server generator and templates based on new output #3261

Merged
merged 6 commits into from
Jul 8, 2019
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,7 @@ Here is a list of template creators:
* JAX-RS RestEasy (JBoss EAP): @jfiala
* Kotlin: @jimschubert [:heart:](https://www.patreon.com/jimschubert)
* Kotlin (Spring Boot): @dr4ke616
* NodeJS Express: @YishTish
* PHP Laravel: @renepardon
* PHP Lumen: @abcsun
* PHP Slim: @jfastnacht
Expand Down
1 change: 1 addition & 0 deletions docs/generators.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ The following generators are available:
- [jaxrs-spec](generators/jaxrs-spec.md)
- [kotlin-server](generators/kotlin-server.md)
- [kotlin-spring](generators/kotlin-spring.md)
- [nodejs-express-server](generators/nodejs-express-server.md) (beta)
- [nodejs-server-deprecated](generators/nodejs-server-deprecated.md) (deprecated)
- [php-laravel](generators/php-laravel.md)
- [php-lumen](generators/php-lumen.md)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
import io.swagger.v3.oas.models.info.Info;
import org.openapitools.codegen.*;
import org.openapitools.codegen.config.GeneratorProperties;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.utils.URLPathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -42,49 +44,25 @@
public class NodeJSExpressServerCodegen extends DefaultCodegen implements CodegenConfig {

private static final Logger LOGGER = LoggerFactory.getLogger(NodeJSExpressServerCodegen.class);
protected String implFolder = "service";
public static final String EXPORTED_NAME = "exportedName";
public static final String SERVER_PORT = "serverPort";

protected String apiVersion = "1.0.0";
protected String projectName = "openapi-server";
protected String defaultServerPort = "8080";

protected boolean googleCloudFunctions;
protected String implFolder = "service";
protected String projectName = "openapi-server";
protected String exportedName;

public NodeJSExpressServerCodegen() {
super();

// set the output folder here
outputFolder = "generated-code/nodejs";

/*
* Models. You can write model files using the modelTemplateFiles map.
* if you want to create one template for file, you can do so here.
* for multiple files for model, just put another entry in the `modelTemplateFiles` with
* a different extension
*/
modelTemplateFiles.clear();

/*
* Api classes. You can write classes for each Api file with the apiTemplateFiles map.
* as with models, add multiple entries with different extensions for multiple files per
* class
*/
apiTemplateFiles.put(
"controller.mustache", // the template to use
".js"); // the extension for each file to write
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.BETA)
.build();

/*
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
embeddedTemplateDir = templateDir = "nodejs";
outputFolder = "generated-code/nodejs-express-server";
embeddedTemplateDir = templateDir = "nodejs-express-server";

/*
* Reserved words. Override this with reserved words specific to your language
*/
setReservedWordsLowerCase(
Arrays.asList(
"break", "case", "class", "catch", "const", "continue", "debugger",
Expand All @@ -94,19 +72,41 @@ public NodeJSExpressServerCodegen() {
"void", "while", "with", "yield")
);

/*
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties.put("apiVersion", apiVersion);
additionalProperties.put("implFolder", implFolder);

supportingFiles.add(new SupportingFile("writer.mustache", ("utils").replace(".", File.separator), "writer.js"));
// no model file
modelTemplateFiles.clear();

apiTemplateFiles.put("controller.mustache", ".js");
apiTemplateFiles.put("service.mustache", ".js");

supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml"));
supportingFiles.add(new SupportingFile("app.mustache", "", "app.js"));
supportingFiles.add(new SupportingFile("config.mustache", "", "config.js"));
supportingFiles.add(new SupportingFile("expressServer.mustache", "", "expressServer.js"));
supportingFiles.add(new SupportingFile("index.mustache", "", "index.js"));
supportingFiles.add(new SupportingFile("logger.mustache", "", "logger.js"));
supportingFiles.add(new SupportingFile("eslintrc.mustache", "", ".eslintrc.json"));

// utils folder
supportingFiles.add(new SupportingFile("utils" + File.separator + "openapiRouter.mustache", "utils", "openapiRouter.js"));
supportingFiles.add(new SupportingFile("utils" + File.separator + "swaggerRouter.mustache", "utils", "swaggerRouter.js"));
supportingFiles.add(new SupportingFile("utils" + File.separator + "writer.mustache", "utils", "writer.js"));

// controllers folder
supportingFiles.add(new SupportingFile("service" + File.separator + "test.mustache", "controllers", "TestController.js"));
supportingFiles.add(new SupportingFile("controllers" + File.separator + "index.mustache", "controllers", "index.js"));
supportingFiles.add(new SupportingFile("controllers" + File.separator + "Controller.mustache", "controllers", "Controller.js"));
// service folder
supportingFiles.add(new SupportingFile("service" + File.separator + "test.mustache", "service", "TestService.js"));
supportingFiles.add(new SupportingFile("service" + File.separator + "index.mustache", "service", "index.js"));
supportingFiles.add(new SupportingFile("service" + File.separator + "Service.mustache", "service", "Service.js"));

// do not overwrite if the file is already present
writeOptional(outputFolder, new SupportingFile("package.mustache", "", "package.json"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));

cliOptions.add(new CliOption(EXPORTED_NAME,
"When the generated code will be deployed to Google Cloud Functions, this option can be "
+ "used to update the name of the exported function. By default, it refers to the "
+ "basePath. This does not affect normal standalone nodejs server code."));
cliOptions.add(new CliOption(SERVER_PORT,
"TCP port to listen on."));
}
Expand Down Expand Up @@ -146,23 +146,22 @@ public String getName() {
*/
@Override
public String getHelp() {
return "Generates a NodeJS Express server (beta).";
return "Generates a NodeJS Express server (beta and may subject to breaking changes without further notice).";
}

@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultController";
return "Default";
}
return camelize(name);
}

@Override
public String toApiFilename(String name) {
return toApiName(name);
return toApiName(name) + "Controller";
}


@Override
public String apiFilename(String templateName, String tag) {
String result = super.apiFilename(templateName, tag);
Expand All @@ -171,13 +170,20 @@ public String apiFilename(String templateName, String tag) {
String stringToMatch = File.separator + "controllers" + File.separator;
String replacement = File.separator + implFolder + File.separator;
result = result.replaceAll(Pattern.quote(stringToMatch), replacement);

stringToMatch = "Controller.js";
replacement = "Service.js";
result = result.replaceAll(Pattern.quote(stringToMatch), replacement);
}
return result;
}

private String implFileFolder(String output) {
/*
@Override
protected String implFileFolder(String output) {
return outputFolder + File.separator + output + File.separator + apiPackage().replace('.', File.separatorChar);
}
*/

/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
Expand All @@ -202,14 +208,6 @@ public String apiFileFolder() {
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}

public boolean getGoogleCloudFunctions() {
return googleCloudFunctions;
}

public void setGoogleCloudFunctions(boolean value) {
googleCloudFunctions = value;
}

public String getExportedName() {
return exportedName;
}
Expand Down Expand Up @@ -304,22 +302,6 @@ public void processOpts() {
// "controllers",
// "controller.js")
// );
supportingFiles.add(new SupportingFile("openapi.mustache",
"api",
"openapi.yaml")
);
if (getGoogleCloudFunctions()) {
writeOptional(outputFolder, new SupportingFile("index-gcf.mustache", "", "index.js"));
} else {
writeOptional(outputFolder, new SupportingFile("index.mustache", "", "index.js"));
}
writeOptional(outputFolder, new SupportingFile("package.mustache", "", "package.json"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
if (GeneratorProperties.getProperty("noservice") == null) {
apiTemplateFiles.put(
"service.mustache", // the template to use
"Service.js"); // the extension for each file to write
}
}

@Override
Expand Down Expand Up @@ -349,22 +331,7 @@ public void preprocessOpenAPI(OpenAPI openAPI) {
}
}

if (getGoogleCloudFunctions()) {
// Note that Cloud Functions don't allow customizing port name, simply checking host
// is good enough.
if (!host.endsWith(".cloudfunctions.net")) {
LOGGER.warn("Host " + host + " seems not matching with cloudfunctions.net URL.");
}
if (!additionalProperties.containsKey(EXPORTED_NAME)) {
if (basePath == null || basePath.equals("/")) {
LOGGER.warn("Cannot find the exported name properly. Using 'openapi' as the exported name");
basePath = "/openapi";
}
additionalProperties.put(EXPORTED_NAME, basePath.substring(1));
}
}

// need vendor extensions for x-swagger-router-controller
// need vendor extensions
Paths paths = openAPI.getPaths();
if (paths != null) {
for (String pathname : paths.keySet()) {
Expand All @@ -380,14 +347,21 @@ public void preprocessOpenAPI(OpenAPI openAPI) {
if (operation.getOperationId() == null) {
operation.setOperationId(getOrGenerateOperationId(operation, pathname, method.toString()));
}
// add x-openapi-router-controller
if (operation.getExtensions() == null ||
operation.getExtensions().get("x-swagger-router-controller") == null) {
operation.addExtension("x-swagger-router-controller", sanitizeTag(tag));
operation.getExtensions().get("x-openapi-router-controller") == null) {
operation.addExtension("x-openapi-router-controller", sanitizeTag(tag) + "Controller");
}
// add x-openapi-router-service
if (operation.getExtensions() == null ||
operation.getExtensions().get("x-openapi-router-service") == null) {
operation.addExtension("x-openapi-router-service", sanitizeTag(tag) + "Service");
}
}
}
}
}

}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const ExpressServer = require('./expressServer');
const logger = require('./logger');
// const swaggerRouter = require('./utils/swaggerRouter');

class App {
constructor(config) {
this.config = config;
}

async launch() {
try {
this.expressServer = new ExpressServer(this.config.URL_PORT, this.config.OPENAPI_YAML);
// this.expressServer.app.use(swaggerRouter());
await this.expressServer.launch();
logger.info('Express server running');
} catch (error) {
logger.error(error);
await this.close();
}
}

async close() {
if (this.expressServer !== undefined) {
await this.expressServer.close();
logger.info(`Server shut down on port ${this.config.URL_PORT}`);
}
}
}

module.exports = App;
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const path = require('path');

const config = {
ROOT_DIR: __dirname,
URL_PORT: 3000,
URL_PATH: 'http://localhost',
BASE_VERSION: 'v2',
CONTROLLER_DIRECTORY: path.join(__dirname, 'controllers'),
};
config.OPENAPI_YAML = path.join(config.ROOT_DIR, 'api', 'openapi.yaml');
config.FULL_PATH = `${config.URL_PATH}:${config.URL_PORT}/${config.BASE_VERSION}`;
module.exports = config;
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
'use strict';
const Controller = require('./Controller');

class {{{classname}}}Controller {
constructor(Service) {
this.service = Service;

var utils = require('../utils/writer.js');
{{#operations}}
var {{classname}} = require('../{{implFolder}}/{{classname}}Service');
{{#operation}}
async {{operationId}}(request, response) {
await Controller.handleRequest(request, response, this.service.{{operationId}});
}

module.exports.{{nickname}} = function {{nickname}} (req, res, next) {
{{#allParams}}
var {{paramName}} = req.swagger.params['{{baseName}}'].value;
{{/allParams}}
{{classname}}.{{nickname}}({{#allParams}}{{paramName}}{{#hasMore}},{{/hasMore}}{{/allParams}})
.then(function (response) {
utils.writeJson(res, response);
})
.catch(function (response) {
utils.writeJson(res, response);
});
};
{{/operation}}
}

module.exports = {{classname}};
{{/operations}}
Loading