@wuapi/generator
Version:
235 lines (234 loc) • 9.36 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const essential_1 = require("@wuapi/essential");
const plugin_base_1 = require("./plugin_base");
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const lodash_1 = __importDefault(require("lodash"));
const plugin_java_1 = __importDefault(require("./plugin_java"));
const brace_1 = require("./brace");
const ncp_1 = __importDefault(require("ncp"));
const demo_generator_1 = __importDefault(require("./spring/demo_generator"));
class SpringPlugin extends plugin_base_1.BasePlugin {
getDescription() {
return {
name: "spring",
abbreviation: "p",
version: "1.0.0",
description: "Generate spring boot codes.",
arguments: [
{
tag: "pkg",
withValue: true,
description: "The package name to spring code, (default to API package)",
},
{
tag: "name",
withValue: true,
description: "The name of the spring project.",
},
{
tag: "api",
withValue: false,
description: "Also generate API code",
},
{
tag: "interface",
withValue: false,
description: "Generate interfaces instead of classes",
},
{
tag: "demo",
withValue: false,
description: "Generate demo (fake) data.",
},
{
tag: "inc",
withValue: false,
description: "Increamental, NOT overriding config files",
},
],
};
}
process(project, outputDir, args) {
if (args["name"] == undefined) {
console.error("ERROR! option '-p' request '--p-name <name>' argument");
console.error("Please check with '-h'");
return;
}
new SpringProcessor(this, project, outputDir, args).process();
}
}
exports.default = SpringPlugin;
class SpringProcessor extends plugin_base_1.ProjectProcessor {
get name() {
return this.config["name"];
}
get useInterface() {
return this.config["interface"] != undefined;
}
get useDemo() {
return this.config["demo"] != undefined;
}
constructor(plugin, project, outputDir, config) {
super(plugin, project, outputDir, config);
this.package = (config["pkg"]) ? config["pkg"] : this.project.targetPackage;
this.packageDir = lodash_1.default.concat([this.rootDir, "src", "main", "java"], this.package.split('.')).join(path_1.default.sep);
}
/**
* Write text into java file.
* @param dir The path of the file.
* @param name The name of this file (without extension).
* @param text The content of the file
*/
writeJavaFile(dir, name, text) {
fs_1.default.mkdirSync(dir, { recursive: true });
const filePath = dir + path_1.default.sep + name + ".java";
const file = fs_1.default.openSync(filePath, 'w');
fs_1.default.writeFileSync(file, text);
}
/**
* Write the application file
*/
writeApplication() {
const _name = lodash_1.default.capitalize(this.name);
this.writeJavaFile(this.packageDir, `${_name}Application`, (0, brace_1.flatBra)("").add((b) => {
b(`package ${this.package};\n`);
b("import org.springframework.boot.SpringApplication;");
b("import org.springframework.boot.autoconfigure.SpringBootApplication;\n");
b("@SpringBootApplication");
b.bra(`public class ${_name}Application `).add((b) => {
b.bra("public static void main(String[] args)").add((b) => {
b(`SpringApplication.run(${_name}Application.class, args);`);
});
});
}).toString());
}
/**
* Write a demo response.
* @param b The BraceCaller object to add content to
* @param project The $Project where the entity can be find
* @param path The $ElementPath of the entity, whose demo will be generated.
*/
writeDemoResponse(b, project, path) {
new demo_generator_1.default(project, path).asFunctionBody(b);
}
/**
* Write a module
* @param mName The name of the module.
*/
writeModule(mName) {
const module = this.project.modules[mName];
const cname = `${this.useInterface ? "I" : ""}${mName}Resource`;
let reqCount = 0;
let moduleContent = (0, brace_1.flatBra)("").add((b) => {
b(`package ${this.package}.${mName.toLowerCase()};\n`);
b("import java.util.*;");
b(`import ${this.project.targetPackage}.*;`);
b("import org.springframework.web.bind.annotation.*;\n");
if (!this.useInterface) {
b("@RestController");
}
b.bra(`public ${this.useInterface ? "interface" : "class"} ${cname}`).add((b) => {
for (let eName in module.entities) {
const entity = module.entities[eName];
if (entity.type != essential_1.$EntityType.REQUEST) {
continue;
}
if (entity.isAbstract) {
continue;
}
let method = "";
switch (entity.method ?? essential_1.$ReqMethod.POST) {
case essential_1.$ReqMethod.GET:
method = "Get";
break;
case essential_1.$ReqMethod.POST:
method = "Post";
break;
case essential_1.$ReqMethod.PUT:
method = "Put";
break;
case essential_1.$ReqMethod.DELETE:
method = "Delete";
break;
}
if (!method) {
continue;
}
const resp = entity.response?.name;
if (!resp) {
continue;
}
b(`@${method}Mapping("${entity.path}")`);
if (this.useInterface) {
b(`public ${resp} do${eName}( ${eName} req);\n`);
}
else {
b.bra(`public ${resp} do${eName}( ${eName} req)`).add((b) => {
if (this.useDemo) {
this.writeDemoResponse(b, this.project, entity.response);
}
else {
b("// TODO: implement this method");
b("return null;");
}
});
}
reqCount++;
}
});
});
if (reqCount > 0) {
const dir = this.packageDir + path_1.default.sep + mName.toLowerCase();
this.writeJavaFile(dir, cname, moduleContent.toString());
}
}
/**
* Write template. Including:
* - pom.xml
* - All files under template/spring/src
*/
writeTemplate() {
const map = {
"{{project_name}}": lodash_1.default.kebabCase(this.name),
"{{project_version}}": this.project.version,
"{{project_package}}": this.package,
"{{project_description}}": "",
};
const src = [__dirname, "..", "template", "spring", "pom.xml"].join(path_1.default.sep);
const dst = [this.rootDir, "pom.xml"].join(path_1.default.sep);
this.plugin.rewriteFile(src, dst, map);
const srcDir = [__dirname, "..", "template", "spring", "src"].join(path_1.default.sep);
const dstDir = [this.rootDir, "src"].join(path_1.default.sep);
(0, ncp_1.default)(srcDir, dstDir, (_) => { });
}
/**
* Process the project.
*/
process() {
// Clean
if (this.config["inc"] == undefined) {
fs_1.default.rmSync(this.rootDir, { recursive: true, force: true });
}
// Write API
if (this.config["api"] != undefined) {
const javaDir = [this.rootDir, "src", "main"].join(path_1.default.sep);
fs_1.default.mkdirSync(javaDir, { recursive: true });
new plugin_java_1.default().process(this.project, javaDir, this.config);
}
// Write modules
for (let mName in this.project.modules) {
this.writeModule(mName);
}
// Write application
this.writeApplication();
// Copy templates
if (this.config["inc"] == undefined) {
this.writeTemplate();
}
}
}