Make Javascript client a Node.js (NPM) module

This commit is contained in:
xhh 2015-12-16 23:51:48 +08:00
parent 625e712d7b
commit 2c1d8b19d2
15 changed files with 286 additions and 85 deletions

View File

@ -35,11 +35,13 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptClientCodegen.class);
private static final String PROJECT_NAME = "projectName";
private static final String MODULE_NAME = "moduleName";
private static final String PROJECT_DESCRIPTION = "projectDescription";
private static final String PROJECT_VERSION = "projectVersion";
private static final String PROJECT_LICENSE_NAME = "projectLicenseName";
protected String projectName = null;
protected String moduleName = null;
protected String projectDescription = null;
protected String projectVersion = null;
@ -52,41 +54,44 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
modelTemplateFiles.put("model.mustache", ".js");
apiTemplateFiles.put("api.mustache", ".js");
templateDir = "Javascript";
apiPackage = "scripts/rest/api";
modelPackage = "scripts/rest/model";
apiPackage = "api";
modelPackage = "model";
// reference: http://www.w3schools.com/js/js_reserved.asp
reservedWords = new HashSet<String>(
Arrays.asList(
"abstract", "continue", "for", "new", "switch", "assert",
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private",
"this", "break", "double", "implements", "protected", "throw", "byte", "else",
"import", "public", "throws", "case", "enum", "instanceof", "return", "transient",
"catch", "extends", "int", "short", "try", "char", "final", "interface", "static",
"void", "class", "finally", "long", "strictfp", "volatile", "const", "float",
"native", "super", "while")
"abstract", "arguments", "boolean", "break", "byte",
"case", "catch", "char", "class", "const",
"continue", "debugger", "default", "delete", "do",
"double", "else", "enum", "eval", "export",
"extends", "false", "final", "finally", "float",
"for", "function", "goto", "if", "implements",
"import", "in", "instanceof", "int", "interface",
"let", "long", "native", "new", "null",
"package", "private", "protected", "public", "return",
"short", "static", "super", "switch", "synchronized",
"this", "throw", "throws", "transient", "true",
"try", "typeof", "var", "void", "volatile",
"while", "with", "yield",
"Array", "Date", "eval", "function", "hasOwnProperty",
"Infinity", "isFinite", "isNaN", "isPrototypeOf",
"Math", "NaN", "Number", "Object",
"prototype", "String", "toString", "undefined", "valueOf")
);
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"Object",
"byte[]")
Arrays.asList("String", "Boolean", "Integer", "Number", "Array", "Object", "Date", "File")
);
instantiationTypes.put("array", "Array");
instantiationTypes.put("map", "HashMap");
defaultIncludes = new HashSet<String>(languageSpecificPrimitives);
cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC));
cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue("src"));
cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC));
cliOptions.add(new CliOption(PROJECT_NAME,
"name of the project (Default: generated from info.title or \"swagger-js-client\")"));
cliOptions.add(new CliOption(MODULE_NAME,
"module name for AMD, Node or globals (Default: generated from <projectName>)"));
cliOptions.add(new CliOption(PROJECT_DESCRIPTION,
"description of the project (Default: using info.description or \"Client library of <projectNname>\")"));
"description of the project (Default: using info.description or \"Client library of <projectName>\")"));
cliOptions.add(new CliOption(PROJECT_VERSION,
"version of the project (Default: using info.version or \"1.0.0\")"));
cliOptions.add(new CliOption(PROJECT_LICENSE_NAME,
@ -111,7 +116,25 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override
public void processOpts() {
super.processOpts();
typeMapping = new HashMap<String, String>();
typeMapping.put("array", "Array");
typeMapping.put("List", "Array");
typeMapping.put("map", "Object");
typeMapping.put("object", "Object");
typeMapping.put("boolean", "Boolean");
typeMapping.put("char", "String");
typeMapping.put("string", "String");
typeMapping.put("short", "Integer");
typeMapping.put("int", "Integer");
typeMapping.put("integer", "Integer");
typeMapping.put("long", "Integer");
typeMapping.put("float", "Number");
typeMapping.put("double", "Number");
typeMapping.put("number", "Number");
typeMapping.put("DateTime", "Date");
importMapping.clear();
}
@Override
@ -121,12 +144,21 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
if (additionalProperties.containsKey(PROJECT_NAME)) {
projectName = ((String) additionalProperties.get(PROJECT_NAME));
}
if (additionalProperties.containsKey(MODULE_NAME)) {
moduleName = ((String) additionalProperties.get(MODULE_NAME));
}
if (additionalProperties.containsKey(PROJECT_DESCRIPTION)) {
projectDescription = ((String) additionalProperties.get(PROJECT_DESCRIPTION));
}
if (additionalProperties.containsKey(PROJECT_VERSION)) {
projectVersion = ((String) additionalProperties.get(PROJECT_VERSION));
}
if (additionalProperties.containsKey(CodegenConstants.LOCAL_VARIABLE_PREFIX)) {
localVariablePrefix = (String) additionalProperties.get(CodegenConstants.LOCAL_VARIABLE_PREFIX);
}
if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
sourceFolder = (String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER);
}
if (swagger.getInfo() != null) {
Info info = swagger.getInfo();
@ -154,6 +186,9 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
if (projectName == null) {
projectName = "swagger-js-client";
}
if (moduleName == null) {
moduleName = camelize(underscore(projectName));
}
if (projectVersion == null) {
projectVersion = "1.0.0";
}
@ -162,8 +197,14 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
}
additionalProperties.put(PROJECT_NAME, projectName);
additionalProperties.put(MODULE_NAME, moduleName);
additionalProperties.put(PROJECT_DESCRIPTION, escapeText(projectDescription));
additionalProperties.put(PROJECT_VERSION, projectVersion);
additionalProperties.put(CodegenConstants.LOCAL_VARIABLE_PREFIX, localVariablePrefix);
additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder);
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js"));
}
@Override
@ -233,6 +274,16 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return toModelName(name);
}
@Override
public String toModelImport(String name) {
return name;
}
@Override
public String toApiImport(String name) {
return name;
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
@ -263,8 +314,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
// added for Javascript
} else if (p instanceof RefProperty) {
RefProperty rp = (RefProperty)p;
return "new " +rp.getSimpleRef() + "()";
RefProperty rp = (RefProperty)p;
return "new " +rp.getSimpleRef() + "()";
}
return super.toDefaultValue(p);
@ -283,8 +334,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
// added for Javascript
} else if (p instanceof RefProperty) {
RefProperty rp = (RefProperty)p;
return ".constructFromObject(data." + name + ");";
RefProperty rp = (RefProperty)p;
return ".constructFromObject(data." + name + ");";
}
return super.toDefaultValueWithParam(name, p);
@ -297,7 +348,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type) || type.indexOf(".") >= 0) {
if (!needToImport(type)) {
return type;
}
} else {
@ -408,7 +459,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
}
protected boolean needToImport(String type) {
return super.needToImport(type) && type.indexOf(".") < 0;
return !defaultIncludes.contains(type)
&& !languageSpecificPrimitives.contains(type);
}
private String findCommonPrefixOfVars(List<String> vars) {
@ -475,14 +527,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return codegenModel;
}
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
public void setLocalVariablePrefix(String localVariablePrefix) {
this.localVariablePrefix = localVariablePrefix;
}
private String sanitizePackageName(String packageName) {
packageName = packageName.trim();
packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_");

View File

@ -1,6 +1,14 @@
//export module
// require files in Node.js environment
{{#imports}}
var {{import}};{{/imports}}
if (typeof module === 'object' && module.exports) {
{{#imports}}
{{import}} = require('./{{import}}.js');{{/imports}}
}
// export module for AMD
if ( typeof define === "function" && define.amd ) {
define(['jquery'], function($) {
define(['jquery'{{#imports}}, '{{import}}'{{/imports}}], function(${{#imports}}, {{import}}{{/imports}}) {
return {{classname}};
});
}
@ -124,3 +132,8 @@ var {{classname}} = function {{classname}}() {
return queryString;
}
}
// export module for Node.js
if (typeof module === 'object' && module.exports) {
module.exports = {{classname}};
}

View File

@ -0,0 +1,10 @@
if (typeof module === 'object' && module.exports) {
var {{moduleName}} = {};
{{#models}}
{{moduleName}}.{{importPath}} = require('./model/{{importPath}}.js');
{{/models}}
{{#apiInfo}}{{#apis}}
{{moduleName}}.{{importPath}} = require('./api/{{importPath}}.js');
{{/apis}}{{/apiInfo}}
module.exports = {{moduleName}};
}

View File

@ -1,10 +1,18 @@
// require files in Node.js environment
{{#imports}}
var {{import}};{{/imports}}
if (typeof module === 'object' && module.exports) {
{{#imports}}
{{import}} = require('./{{import}}.js');{{/imports}}
}
{{#models}}{{#model}}
{{#vars}}{{#isEnum}}{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}}
{{>enumClass}}{{/items}}*/{{/items.isEnum}}{{/vars}}
//export module
if ( typeof define === "function" && define.amd ) {
define('{{classname}}', ['jquery'{{#vars}}{{^isPrimitiveType}}{{^-last}}, {{/-last}}'{{datatypeWithEnum}}'{{/isPrimitiveType}}{{/vars}}],
if ( typeof define === "function" && define.amd ) {
define('{{classname}}', ['jquery'{{#vars}}{{^isPrimitiveType}}{{^-last}}, {{/-last}}'{{datatypeWithEnum}}'{{/isPrimitiveType}}{{/vars}}],
function(${{#vars}}{{^isPrimitiveType}}{{^-last}}, {{/-last}}{{datatypeWithEnum}}{{/isPrimitiveType}}{{/vars}}) {
return {{classname}};
});
@ -56,5 +64,9 @@ var {{classname}} = function {{classname}}({{#mandatory}}{{this}}{{^-last}}, {{/
return JSON.stringify(self);
}
}
if (typeof module === 'object' && module.exports) {
module.exports = {{classname}};
}
{{/model}}
{{/models}}

View File

@ -3,7 +3,7 @@
"version": "{{{projectVersion}}}",
"description": "{{{projectDescription}}}",{{#projectLicenseName}}
"license": "{{{projectLicenseName}}}",{{/projectLicenseName}}
"main": "index.js",
"main": "{{sourceFolder}}/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},

View File

@ -0,0 +1,13 @@
{
"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": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"jquery": "^2.1.4"
}
}

View File

@ -1,6 +1,13 @@
//export module
// require files in Node.js environment
var Pet;
if (typeof module === 'object' && module.exports) {
Pet = require('./Pet.js');
}
// export module for AMD
if ( typeof define === "function" && define.amd ) {
define(['jquery'], function($) {
define(['jquery', 'Pet'], function($, Pet) {
return PetApi;
});
}
@ -243,7 +250,7 @@ var PetApi = function PetApi() {
/**
* Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param {Long} petId ID of pet that needs to be fetched
* @param {Integer} petId ID of pet that needs to be fetched
* @param {function} callback the callback function
* @return Pet
*/
@ -379,7 +386,7 @@ var PetApi = function PetApi() {
/**
* Deletes a pet
*
* @param {Long} petId Pet id to delete
* @param {Integer} petId Pet id to delete
* @param {String} apiKey
* @param {function} callback the callback function
* @return void
@ -437,7 +444,7 @@ var PetApi = function PetApi() {
/**
* uploads an image
*
* @param {Long} petId ID of pet to update
* @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
@ -522,3 +529,8 @@ var PetApi = function PetApi() {
return queryString;
}
}
// export module for Node.js
if (typeof module === 'object' && module.exports) {
module.exports = PetApi;
}

View File

@ -1,6 +1,13 @@
//export module
// require files in Node.js environment
var Order;
if (typeof module === 'object' && module.exports) {
Order = require('./Order.js');
}
// export module for AMD
if ( typeof define === "function" && define.amd ) {
define(['jquery'], function($) {
define(['jquery', 'Order'], function($, Order) {
return StoreApi;
});
}
@ -12,7 +19,7 @@ var StoreApi = function StoreApi() {
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @param {function} callback the callback function
* @return Map<String, Integer>
* @return Object<String, Integer>
*/
self.getInventory = function(callback) {
@ -47,7 +54,7 @@ var StoreApi = function StoreApi() {
//TypeRef returnType = new TypeRef<Map<String, Integer>>() {};
//TypeRef returnType = new TypeRef<Object<String, Integer>>() {};
//return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType);
var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody};
@ -59,11 +66,10 @@ var StoreApi = function StoreApi() {
request.done(function(response, textStatus, jqXHR){
/**
* @returns Map<String, Integer>
* @returns Object<String, Integer>
*/
var myResponse = response;
var myResponse = new Map<String, Integer>();
myResponse.constructFromObject(response);
callback(myResponse, textStatus, jqXHR);
});
@ -298,3 +304,8 @@ var StoreApi = function StoreApi() {
return queryString;
}
}
// export module for Node.js
if (typeof module === 'object' && module.exports) {
module.exports = StoreApi;
}

View File

@ -1,6 +1,13 @@
//export module
// require files in Node.js environment
var User;
if (typeof module === 'object' && module.exports) {
User = require('./User.js');
}
// export module for AMD
if ( typeof define === "function" && define.amd ) {
define(['jquery'], function($) {
define(['jquery', 'User'], function($, User) {
return UserApi;
});
}
@ -479,3 +486,8 @@ var UserApi = function UserApi() {
return queryString;
}
}
// export module for Node.js
if (typeof module === 'object' && module.exports) {
module.exports = UserApi;
}

View File

@ -0,0 +1,22 @@
if (typeof module === 'object' && module.exports) {
var SwaggerPetstore = {};
SwaggerPetstore.User = require('./model/User.js');
SwaggerPetstore.Category = require('./model/Category.js');
SwaggerPetstore.Pet = require('./model/Pet.js');
SwaggerPetstore.Tag = require('./model/Tag.js');
SwaggerPetstore.Order = require('./model/Order.js');
SwaggerPetstore.User = require('./api/User.js');
SwaggerPetstore.Store = require('./api/Store.js');
SwaggerPetstore.Pet = require('./api/Pet.js');
module.exports = SwaggerPetstore;
}

View File

@ -1,9 +1,15 @@
// require files in Node.js environment
if (typeof module === 'object' && module.exports) {
}
//export module
if ( typeof define === "function" && define.amd ) {
define('Category', ['jquery'],
if ( typeof define === "function" && define.amd ) {
define('Category', ['jquery'],
function($) {
return Category;
});
@ -14,7 +20,7 @@ var Category = function Category() {
var self = this;
/**
* datatype: Long
* datatype: Integer
**/
self.id = null;
@ -34,14 +40,14 @@ var Category = function Category() {
/**
* @return {Long}
* @return {Integer}
**/
self.getId = function() {
return self.id;
}
/**
* @param {Long} id
* @param {Integer} id
**/
self.setId = function (id) {
self.id = id;
@ -66,3 +72,7 @@ var Category = function Category() {
return JSON.stringify(self);
}
}
if (typeof module === 'object' && module.exports) {
module.exports = Category;
}

View File

@ -1,3 +1,9 @@
// require files in Node.js environment
if (typeof module === 'object' && module.exports) {
}
//export module
@ -30,9 +36,9 @@ var StatusEnum = function StatusEnum() {
//export module
if ( typeof define === "function" && define.amd ) {
define('Order', ['jquery', 'Date'],
function($, Date) {
if ( typeof define === "function" && define.amd ) {
define('Order', ['jquery'],
function($) {
return Order;
});
}
@ -42,12 +48,12 @@ var Order = function Order() {
var self = this;
/**
* datatype: Long
* datatype: Integer
**/
self.id = null;
/**
* datatype: Long
* datatype: Integer
**/
self.petId = null;
@ -91,28 +97,28 @@ var Order = function Order() {
/**
* @return {Long}
* @return {Integer}
**/
self.getId = function() {
return self.id;
}
/**
* @param {Long} id
* @param {Integer} id
**/
self.setId = function (id) {
self.id = id;
}
/**
* @return {Long}
* @return {Integer}
**/
self.getPetId = function() {
return self.petId;
}
/**
* @param {Long} petId
* @param {Integer} petId
**/
self.setPetId = function (petId) {
self.petId = petId;
@ -181,3 +187,7 @@ var Order = function Order() {
return JSON.stringify(self);
}
}
if (typeof module === 'object' && module.exports) {
module.exports = Order;
}

View File

@ -1,3 +1,11 @@
// require files in Node.js environment
var Category;var Tag;
if (typeof module === 'object' && module.exports) {
Category = require('./Category.js');
Tag = require('./Tag.js');
}
//export module
@ -30,8 +38,8 @@ var StatusEnum = function StatusEnum() {
//export module
if ( typeof define === "function" && define.amd ) {
define('Pet', ['jquery', 'Category', 'Array'],
if ( typeof define === "function" && define.amd ) {
define('Pet', ['jquery', 'Category', 'Array'],
function($, Category, Array) {
return Pet;
});
@ -42,7 +50,7 @@ var Pet = function Pet(photoUrls, name) {
var self = this;
/**
* datatype: Long
* datatype: Integer
**/
self.id = null;
@ -93,14 +101,14 @@ var Pet = function Pet(photoUrls, name) {
/**
* @return {Long}
* @return {Integer}
**/
self.getId = function() {
return self.id;
}
/**
* @param {Long} id
* @param {Integer} id
**/
self.setId = function (id) {
self.id = id;
@ -183,3 +191,7 @@ var Pet = function Pet(photoUrls, name) {
return JSON.stringify(self);
}
}
if (typeof module === 'object' && module.exports) {
module.exports = Pet;
}

View File

@ -1,9 +1,15 @@
// require files in Node.js environment
if (typeof module === 'object' && module.exports) {
}
//export module
if ( typeof define === "function" && define.amd ) {
define('Tag', ['jquery'],
if ( typeof define === "function" && define.amd ) {
define('Tag', ['jquery'],
function($) {
return Tag;
});
@ -14,7 +20,7 @@ var Tag = function Tag() {
var self = this;
/**
* datatype: Long
* datatype: Integer
**/
self.id = null;
@ -34,14 +40,14 @@ var Tag = function Tag() {
/**
* @return {Long}
* @return {Integer}
**/
self.getId = function() {
return self.id;
}
/**
* @param {Long} id
* @param {Integer} id
**/
self.setId = function (id) {
self.id = id;
@ -66,3 +72,7 @@ var Tag = function Tag() {
return JSON.stringify(self);
}
}
if (typeof module === 'object' && module.exports) {
module.exports = Tag;
}

View File

@ -1,9 +1,15 @@
// require files in Node.js environment
if (typeof module === 'object' && module.exports) {
}
//export module
if ( typeof define === "function" && define.amd ) {
define('User', ['jquery'],
if ( typeof define === "function" && define.amd ) {
define('User', ['jquery'],
function($) {
return User;
});
@ -14,7 +20,7 @@ var User = function User() {
var self = this;
/**
* datatype: Long
* datatype: Integer
**/
self.id = null;
@ -77,14 +83,14 @@ var User = function User() {
/**
* @return {Long}
* @return {Integer}
**/
self.getId = function() {
return self.id;
}
/**
* @param {Long} id
* @param {Integer} id
**/
self.setId = function (id) {
self.id = id;
@ -195,3 +201,7 @@ var User = function User() {
return JSON.stringify(self);
}
}
if (typeof module === 'object' && module.exports) {
module.exports = User;
}