very-express 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/.env +3 -4
  2. package/.eslintrc.json +37 -37
  3. package/LICENSE +1 -1
  4. package/README.md +15 -35
  5. package/dist/cli.js +41 -37
  6. package/dist/generators/controller.template.js +27 -8
  7. package/dist/generators/controllers.generator.js +17 -20
  8. package/dist/generators/openapi.generator.d.ts +1 -4
  9. package/dist/generators/openapi.generator.js +8 -8
  10. package/dist/generators/packageJson.generator.d.ts +1 -1
  11. package/dist/generators/packageJson.generator.js +10 -10
  12. package/dist/generators/routes/oauth.generator.d.ts +4 -0
  13. package/dist/generators/routes/oauth.generator.js +46 -0
  14. package/dist/generators/routes.generator.d.ts +1 -1
  15. package/dist/generators/routes.generator.js +39 -3
  16. package/dist/generators/routes.template.js +11 -32
  17. package/dist/generators/server.generator.d.ts +1 -1
  18. package/dist/generators/server.generator.js +12 -15
  19. package/dist/generators/server.template.d.ts +2 -2
  20. package/dist/generators/server.template.js +111 -15
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +15 -23
  23. package/dist/preprocess/jsonschemaFormat.js +10 -7
  24. package/dist/templates/jsonSchema/User.json +51 -0
  25. package/dist/templates/plugins/PassportGoogle.gen.ts +64 -0
  26. package/dist/templates/plugins/oauthVerify.gen.ts +33 -0
  27. package/dist/templates/root/.env +6 -2
  28. package/dist/templates/root/package.json +6 -5
  29. package/dist/templates/routes/swagger.gen.ts +17 -0
  30. package/dist/templates/services/mongoConn.gen.ts +25 -0
  31. package/dist/templates/utils/common.gen.ts +9 -2
  32. package/dist/templates/utils/logger.gen.ts +23 -0
  33. package/dist/types/types.d.ts +13 -4
  34. package/dist/utils/common.d.ts +3 -1
  35. package/dist/utils/common.js +26 -11
  36. package/dist/utils/logger.d.ts +13 -0
  37. package/dist/utils/logger.js +31 -0
  38. package/package.json +3 -3
  39. package/vex.config.json +10 -2
package/.env CHANGED
@@ -1,4 +1,3 @@
1
-
2
- G_OAUTH_CLIENTID=997485928958-ep5gd9gf25rs5lkpnau5r5q50729utrf.apps.googleusercontent.com
3
- G_OAUTH_CLIENTSECRET=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
4
- # veryExpress generated
1
+ # veryExpress generated
2
+ EXPRESS_PORT=3000
3
+ MONGO_URL=mongodb://localhost:27017/veryExpressDB
package/.eslintrc.json CHANGED
@@ -1,37 +1,37 @@
1
- {
2
- "env": {
3
- "browser": true,
4
- "es2021": true
5
- },
6
- "extends": [
7
- "eslint:recommended",
8
- "plugin:@typescript-eslint/recommended"
9
- ],
10
- "parser": "@typescript-eslint/parser",
11
- "parserOptions": {
12
- "ecmaVersion": "latest",
13
- "sourceType": "module"
14
- },
15
- "plugins": [
16
- "@typescript-eslint"
17
- ],
18
- "rules": {
19
- "@typescript-eslint/no-explicit-any": "off",
20
- "indent": [
21
- "error",
22
- 4
23
- ],
24
- "linebreak-style": [
25
- "error",
26
- "unix"
27
- ],
28
- "quotes": [
29
- "error",
30
- "double"
31
- ],
32
- "semi": [
33
- "error",
34
- "always"
35
- ]
36
- }
37
- }
1
+ {
2
+ "env": {
3
+ "browser": true,
4
+ "es2021": true
5
+ },
6
+ "extends": [
7
+ "eslint:recommended",
8
+ "plugin:@typescript-eslint/recommended"
9
+ ],
10
+ "parser": "@typescript-eslint/parser",
11
+ "parserOptions": {
12
+ "ecmaVersion": "latest",
13
+ "sourceType": "module"
14
+ },
15
+ "plugins": [
16
+ "@typescript-eslint"
17
+ ],
18
+ "rules": {
19
+ "@typescript-eslint/no-explicit-any": "off",
20
+ "indent": [
21
+ "error",
22
+ 4
23
+ ],
24
+ "linebreak-style": [
25
+ "error",
26
+ "unix"
27
+ ],
28
+ "quotes": [
29
+ "error",
30
+ "double"
31
+ ],
32
+ "semi": [
33
+ "error",
34
+ "always"
35
+ ]
36
+ }
37
+ }
package/LICENSE CHANGED
@@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
18
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
21
+ SOFTWARE.
package/README.md CHANGED
@@ -54,43 +54,23 @@ at the properites :
54
54
 
55
55
  ## Road Map
56
56
  - [ ] dockernize
57
- - [x] generate express server
58
- - [x] gen. routes
59
- - [x] gen. controllers based on openapi spec
60
- - [ ] define fields searching method
61
- - [x] gen. openapi based on json schema
62
- - [x] gen. mongoose model
63
- - [ ] gen. sql model
64
- - [ ] database connection
65
- - [ ] implement sensitive data encryption & hash (PDPA)
66
- - [x] TS interface based on json schema
57
+ - [x] generate express app
58
+ - [x] gen. openapi based on json schema
59
+ - [x] gen. controllers based on openapi
60
+ - [x] CRUD + Search api
61
+ - [ ] database
62
+ - [x] mongodb
63
+ - [ ] sql
64
+ - [ ] db encrtption [PDPA](https://en.wikipedia.org/wiki/Personal_Data_Protection_Act_2012)
65
+ - [ ] oauth2
66
+ - [ ] google
67
+ - [ ] microsoft
68
+ - [ ] github
69
+ - [ ] Role Base Access Control
67
70
 
68
71
  ## Enhancement To Do
69
- - avoid mongo `_id` , instead using custom index `id` for db compatibilities,
70
- - at JsonSchmea.x-documentConfig, add fields
71
- `index: string` point to index fields,
72
- `indexPrefix: string` for easier to identify if its is a foreignKey value.
73
72
 
74
73
  - Implement data encryption & hash (PDPA)
75
- - at JsonSchmea.Properties, add attribute
76
- `x-dataSecure: sting` while accessing data, perform hash or encryption.
77
-
78
- - `* TBC *` Controller > define fields searching method
79
- - at JsonSchmea.x-Properties, add attribute
80
- `x-filterType: obejct` method will be array of [ "equal", "like", "between", "gratherThan", "smallerThen" ] default "equal" :
81
-
82
- "date":{
83
- "type": "string",
84
- "format": "date-time",
85
-
86
- "x-filterType": {
87
- method : "between",
88
- from : 'startDate', // additinal fields at openapi /get
89
- to : 'endDate', // additinal fields at openapi /get
90
- },
91
-
92
- "x-filterType": {
93
- method : "like",
94
- },
95
- }
74
+ - at JsonSchmea fields, add attribute
75
+ `x-dataSecure: "method"` while accessing data, perform encryption based on method selected.
96
76
 
package/dist/cli.js CHANGED
@@ -5,64 +5,68 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  };
6
6
  var _a;
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
- const index_1 = __importDefault(require("./index"));
9
8
  const fs_1 = __importDefault(require("fs"));
10
9
  const child_process_1 = __importDefault(require("child_process"));
11
10
  const minimist_1 = __importDefault(require("minimist"));
12
- const log_1 = __importDefault(require("./utils/log"));
11
+ const index_1 = require("./index");
12
+ const logger_1 = __importDefault(require("./utils/logger"));
13
+ const common_1 = require("./utils/common");
14
+ console.log("\x1b[35m%s\x1b[0m", "\n========== veryExpress CLI (vex) Start ==========\n");
13
15
  const args = (0, minimist_1.default)(process.argv.slice(2));
14
- let config = {};
16
+ let config = common_1.defaultCompilerOptions;
15
17
  if (fs_1.default.existsSync("vex.config.json")) {
16
18
  try {
17
19
  config = JSON.parse(fs_1.default.readFileSync("vex.config.json", "utf8"));
18
20
  }
19
21
  catch (err) {
20
- log_1.default.error("failed to parse vex.config.json", err);
22
+ logger_1.default.error("failed to parse vex.config.json", err);
21
23
  process.exit(1);
22
24
  }
23
25
  }
24
26
  config.commitBeforeGenerate = (_a = config.commitBeforeGenerate) !== null && _a !== void 0 ? _a : false;
25
27
  config.jsonSchemaDir = args.j || args.jsonSchemaDir || config.jsonSchemaDir || "./jsonSchema";
26
- config.openapiDir = args.a || args.openapiDir || config.openapiDir || "./openapi";
27
28
  config.rootDir = args.o || args.rootDir || config.rootDir || ".";
28
- config.srcDir = (args.s || args.srcDir || config.srcDir || (args.o || args.rootDir || config.rootDir || ".") + "/src");
29
- console.log("\x1b[35m%s\x1b[0m", "\n========== veryExpress CLI (vex) Start ==========\n");
30
- log_1.default.writing("vex.config.json");
29
+ config.srcDir = config.srcDir || config.rootDir + "/src";
30
+ config.openapiDir = config.openapiDir || config.rootDir + "./openapi";
31
+ config.useOauth = config.useOauth || {
32
+ google: false,
33
+ microsoft: false,
34
+ apple: false,
35
+ github: false
36
+ };
37
+ logger_1.default.writing("vex.config.json");
31
38
  fs_1.default.writeFileSync("vex.config.json", JSON.stringify(config, null, 4));
32
- if ("h" in args) {
33
- console.log(`
34
- Usage: vex [jsonSchemaDir] [openapiDir] [rootDir]
35
- -h : Help
36
- -j : jsonSchemaDir (config: ${config.jsonSchemaDir})
37
- -a : openapiDir (config: ${config.openapiDir})
38
- -o : rootDir (config: ${config.rootDir})
39
+ if (["help", "-h", "h"].includes(String(args._[0]).toLowerCase())) {
40
+ console.log(`Very Express CLI Usage :
41
+ vex [flag]
42
+ -h | help : Help
43
+ -i | init : Create generator config etc.
44
+ to generate app :
45
+ vex [jsonSchemaDir] [rootDir]
46
+ -j : jsonSchemaDir (configured: ${config.jsonSchemaDir})
47
+ -o : rootDir (configured: ${config.rootDir})
39
48
  `);
40
49
  process.exit(0);
41
50
  }
42
- if (!fs_1.default.existsSync(config.jsonSchemaDir)) {
43
- log_1.default.error("Schema Dir Not Found:", config.jsonSchemaDir);
44
- process.exit(1);
45
- }
46
- if (!fs_1.default.existsSync(config.rootDir)) {
47
- fs_1.default.mkdirSync(config.rootDir);
48
- }
49
- if (!fs_1.default.existsSync(config.srcDir)) {
50
- fs_1.default.mkdirSync(config.srcDir);
51
+ else if (["init", "-i", "i"].includes(String(args._[0]).toLowerCase())) {
52
+ console.log("Very Express CLI : Initialization ...");
53
+ process.exit(0);
51
54
  }
52
- if (config.commitBeforeGenerate === true) {
53
- try {
54
- log_1.default.info("git commit \"before vex-gen\"");
55
- child_process_1.default.execSync("git add . && git commit -m \"before vex-gen\"", { stdio: "inherit" });
55
+ else {
56
+ if (!fs_1.default.existsSync(config.jsonSchemaDir)) {
57
+ logger_1.default.error("Schema Dir Not Found:", config.jsonSchemaDir);
58
+ process.exit(1);
56
59
  }
57
- catch (err) {
58
- log_1.default.error("git commit \"before vex-gen\" failed", err);
60
+ if (config.commitBeforeGenerate === true) {
61
+ try {
62
+ logger_1.default.info("git commit \"before vex-gen\"");
63
+ child_process_1.default.execSync("git add . && git commit -m \"before vex-gen\"", { stdio: "inherit" });
64
+ }
65
+ catch (err) {
66
+ logger_1.default.error("git commit \"before vex-gen\" failed", err);
67
+ }
59
68
  }
69
+ (0, index_1.generate)(config);
70
+ console.log("\x1b[36m%s\x1b[0m", "\nnext step:\n", `cd ${config.rootDir}\n`, "npm install\n", "npm run dev");
60
71
  }
61
- (0, index_1.default)({
62
- jsonSchemaDir: config.jsonSchemaDir,
63
- openapiDir: config.openapiDir,
64
- rootDir: config.rootDir,
65
- srcDir: config.srcDir,
66
- });
67
72
  console.log("\x1b[35m%s\x1b[0m", "\n========== veryExpress CLI (vex) Complete ==========\n");
68
- console.log("\x1b[36m%s\x1b[0m", "\nnext step:\n", `cd ${config.rootDir}\n`, "npm install\n", "npm run dev");
@@ -13,6 +13,7 @@ function controllerTemplate(templateOptions) {
13
13
  import { Router, Request, Response } from 'express';
14
14
  import { checkSchema, validationResult } from 'express-validator';
15
15
  import { parseFieldsSelect } from '../utils/common.gen';
16
+ import MongoQS from 'mongo-ts-querystring';
16
17
 
17
18
  import { {{interfaceName}}Model } from '{{modelPath}}';
18
19
 
@@ -46,6 +47,7 @@ class {{interfaceName}}Controller {
46
47
  if ( ! validationError.isEmpty() ) {
47
48
  return res.status(400).json(validationError.array());
48
49
  };
50
+
49
51
  const result = await {{interfaceName}}Model.findById(req.params.id);
50
52
  if (!result) {
51
53
  return res.status(404).json({ error: "no data found" });
@@ -65,14 +67,13 @@ class {{interfaceName}}Controller {
65
67
  return res.status(400).json(validationError.array());
66
68
  };
67
69
 
68
- // Get the selected fields from query string
69
- const fields = req.query.fields as string | undefined;
70
- const selectFields = ! fields ? undefined : await parseFieldsSelect(fields)
71
- .catch((err) => {
72
- return res.status(400).json({ error: err });
73
- });
74
-
75
- const result = await {{interfaceName}}Model.find({}, selectFields);
70
+ // Get mongoose filter query
71
+ const searchFilter = new MongoQS().parse(req.query);
72
+
73
+ // Get selected fields from query string
74
+ const selectedFields = await parseFieldsSelect(req.query.select);
75
+
76
+ const result = await {{interfaceName}}Model.find(searchFilter, selectedFields);
76
77
  if (!result) {
77
78
  return res.status(404).json({ error: "no data found" });
78
79
  }
@@ -121,6 +122,24 @@ class {{interfaceName}}Controller {
121
122
  }
122
123
  }
123
124
 
125
+ public async replace{{interfaceName}}(req: Request, res: Response): Promise<Response> {
126
+ try {
127
+ const validationError = validationResult(req);
128
+ if ( ! validationError.isEmpty() ) {
129
+ return res.status(400).json(validationError.array());
130
+ };
131
+ const result = await {{interfaceName}}Model.replaceOne({_id: req.params.id}, req.body);
132
+ if (!result) {
133
+ return res.status(404).json({ error: "failed to update" });
134
+ }
135
+ else {
136
+ return res.status(200).json(result);
137
+ };
138
+ } catch (err:any) {
139
+ return res.status(500).json({ error: err.message });
140
+ }
141
+ }
142
+
124
143
  public async delete{{interfaceName}}(req: Request, res: Response): Promise<Response> {
125
144
  try {
126
145
  const validationError = validationResult(req);
@@ -30,7 +30,7 @@ exports.compile = void 0;
30
30
  const fs_1 = __importDefault(require("fs"));
31
31
  const js_yaml_1 = __importDefault(require("js-yaml"));
32
32
  const controller_template_1 = __importDefault(require("./controller.template"));
33
- const log_1 = __importDefault(require("../utils/log"));
33
+ const logger_1 = __importDefault(require("../utils/logger"));
34
34
  const utils = __importStar(require("../utils/common"));
35
35
  const types = __importStar(require("../types/types"));
36
36
  function compile(options) {
@@ -41,12 +41,12 @@ function compile(options) {
41
41
  const writtedEndpoint = [];
42
42
  Object.keys(openApi.paths).forEach((endpoint) => {
43
43
  endpointsValidator[endpoint] = {};
44
- log_1.default.process(`Controller : ${options.compilerOptions.openapiDir} > ${endpoint}`);
44
+ logger_1.default.process(`Controller : ${options.compilerOptions.openapiDir} > ${endpoint}`);
45
45
  Object.keys(openApi.paths[endpoint]).forEach((httpMethod) => {
46
46
  if (!Object.values(types.httpMethodArr).includes(httpMethod))
47
47
  return;
48
48
  const methodEnum = httpMethod;
49
- const validators = Object.assign(buildParamValidator(endpoint, methodEnum, openApi, options.compilerOptions), buildBodyValidator(endpoint, methodEnum, openApi));
49
+ const validators = Object.assign(buildParamValidator(endpoint, methodEnum, openApi), buildBodyValidator(endpoint, methodEnum, openApi));
50
50
  endpointsValidator[endpoint][httpMethod] = validators;
51
51
  });
52
52
  });
@@ -55,11 +55,11 @@ function compile(options) {
55
55
  const interfaceName = openApi.paths[endpoint]["x-interface"];
56
56
  const endpointFormatted = endpoint.replace("/{id}", "").toLowerCase();
57
57
  if (collectionName === undefined) {
58
- log_1.default.error(`"x-collection" not found in openapi spec's path "${endpoint}"\n - opanapi source: ${options.compilerOptions.openapiDir}`);
58
+ logger_1.default.error(`"x-collection" not found in openapi spec's path "${endpoint}"\n - opanapi source: ${options.compilerOptions.openapiDir}`);
59
59
  return;
60
60
  }
61
61
  else if (interfaceName === undefined) {
62
- log_1.default.error(`"x-interface" not found in openapi spec's path "${endpoint}"\n - opanapi source: ${options.compilerOptions.openapiDir}`);
62
+ logger_1.default.error(`"x-interface" not found in openapi spec's path "${endpoint}"\n - opanapi source: ${options.compilerOptions.openapiDir}`);
63
63
  return;
64
64
  }
65
65
  else if (writtedEndpoint.includes(endpointFormatted)) {
@@ -67,27 +67,24 @@ function compile(options) {
67
67
  }
68
68
  else {
69
69
  const outPath = `${options.controllerOutDir}/${interfaceName}Controller.gen.ts`;
70
- const outPathNoGen = `${options.controllerOutDir}/${interfaceName}Controller.nogen.ts`;
71
70
  const controllerToModelPath = `${controllerToModelBasePath}/${interfaceName}Model.gen`;
72
- if (!fs_1.default.existsSync(outPathNoGen)) {
73
- log_1.default.writing(`Controller : ${outPath}`);
74
- writtedEndpoint.push(endpointFormatted);
75
- fs_1.default.writeFileSync(outPath, (0, controller_template_1.default)({
76
- endpoint: endpoint,
77
- modelPath: controllerToModelPath,
78
- interfaceName: interfaceName,
79
- validators: endpointsValidator,
80
- compilerOptions: options.compilerOptions,
81
- }));
82
- }
71
+ logger_1.default.writing(`Controller : ${outPath}`);
72
+ fs_1.default.writeFileSync(outPath, (0, controller_template_1.default)({
73
+ endpoint: endpoint,
74
+ modelPath: controllerToModelPath,
75
+ interfaceName: interfaceName,
76
+ validators: endpointsValidator,
77
+ compilerOptions: options.compilerOptions,
78
+ }));
79
+ writtedEndpoint.push(endpointFormatted);
83
80
  }
84
81
  });
85
82
  }
86
83
  exports.compile = compile;
87
- function buildParamValidator(endpoint, httpMethod, openapi, compilerOptions) {
84
+ function buildParamValidator(endpoint, httpMethod, openapi) {
88
85
  const validators = {};
89
86
  openapi.paths[endpoint][httpMethod].parameters.forEach((parameter) => {
90
- if (!compilerOptions.use_id && parameter.name === "_id") {
87
+ if (parameter.name === "_id") {
91
88
  return;
92
89
  }
93
90
  Object.assign(validators, processSchema({
@@ -120,7 +117,7 @@ function processSchema(options) {
120
117
  const validators = {
121
118
  [options.fieldName]: {
122
119
  in: options.param ? "params" : options.body ? "body" : [],
123
- optional: !options.required ? true : { options: { values: "falsy", checkFalsy: true } },
120
+ optional: !options.required ? { options: { values: "falsy", checkFalsy: true } } : false,
124
121
  notEmpty: true,
125
122
  },
126
123
  };
@@ -1,6 +1,3 @@
1
1
  import * as types from "../types/types";
2
- export declare function compile(options: {
3
- openapiOutFileName: string;
4
- compilerOptions: types.compilerOptions;
5
- }): void;
2
+ export declare function compile(openapiOutFileName: string, compilerOptions: types.compilerOptions): void;
6
3
  export default compile;
@@ -8,8 +8,8 @@ const json_schema_to_openapi_schema_1 = __importDefault(require("json-schema-to-
8
8
  const js_yaml_1 = __importDefault(require("js-yaml"));
9
9
  const fs_1 = __importDefault(require("fs"));
10
10
  const common_1 = __importDefault(require("../utils/common"));
11
- const log_1 = __importDefault(require("../utils/log"));
12
- function compile(options) {
11
+ const logger_1 = __importDefault(require("../utils/logger"));
12
+ function compile(openapiOutFileName, compilerOptions) {
13
13
  let openapiJson = {
14
14
  openapi: "3.0.0",
15
15
  info: {
@@ -22,21 +22,21 @@ function compile(options) {
22
22
  schemas: {},
23
23
  },
24
24
  };
25
- const files = fs_1.default.readdirSync(options.compilerOptions.jsonSchemaDir);
25
+ const files = fs_1.default.readdirSync(compilerOptions.jsonSchemaDir);
26
26
  files.forEach((file) => {
27
27
  if (!file.endsWith(".json"))
28
28
  return;
29
- const jsonSchemaFilePath = options.compilerOptions.jsonSchemaDir + "/" + file;
30
- log_1.default.process(`OpenApi : ${jsonSchemaFilePath}`);
31
- const jsonSchemaBuffer = fs_1.default.readFileSync(`${options.compilerOptions.jsonSchemaDir}/${file}`);
29
+ const jsonSchemaFilePath = compilerOptions.jsonSchemaDir + "/" + file;
30
+ logger_1.default.process(`OpenApi : ${jsonSchemaFilePath}`);
31
+ const jsonSchemaBuffer = fs_1.default.readFileSync(`${compilerOptions.jsonSchemaDir}/${file}`);
32
32
  const jsonSchema = JSON.parse(jsonSchemaBuffer.toString());
33
33
  openapiJson = jsonToOpenapiPath(openapiJson, jsonSchema, { jsonSchemaFilePath: jsonSchemaFilePath });
34
34
  openapiJson = jsonToOpenapiComponentSchema(openapiJson, jsonSchema, { jsonSchemaFilePath: jsonSchemaFilePath });
35
35
  });
36
36
  const validOpenApi = (0, json_schema_to_openapi_schema_1.default)(openapiJson, { version: 3.0 });
37
37
  const openapiYaml = js_yaml_1.default.dump(validOpenApi);
38
- const openapiOutFile = options.compilerOptions.openapiDir + options.openapiOutFileName;
39
- log_1.default.writing(`OpenApi : ${openapiOutFile}`);
38
+ const openapiOutFile = compilerOptions.openapiDir + openapiOutFileName;
39
+ logger_1.default.writing(`OpenApi : ${openapiOutFile}`);
40
40
  fs_1.default.writeFileSync(openapiOutFile, openapiYaml);
41
41
  }
42
42
  exports.compile = compile;
@@ -1,4 +1,4 @@
1
- export declare function compile(packageOutPath: string, schemaDir: string, openapiDir: string, outDir: string): void;
1
+ export declare function compile(packageOutPath: string, schemaDir: string, outDir: string): void;
2
2
  declare const _default: {
3
3
  compile: typeof compile;
4
4
  };
@@ -5,9 +5,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.compile = void 0;
7
7
  const fs_1 = __importDefault(require("fs"));
8
- const log_1 = __importDefault(require("../utils/log"));
9
- function compile(packageOutPath, schemaDir, openapiDir, outDir) {
10
- log_1.default.process(`Project : ${packageOutPath}`);
8
+ const logger_1 = __importDefault(require("../utils/logger"));
9
+ function compile(packageOutPath, schemaDir, outDir) {
10
+ logger_1.default.process(`Project : ${packageOutPath}`);
11
11
  let writePackage = false;
12
12
  let packjson = "";
13
13
  if (!fs_1.default.existsSync(packageOutPath)) {
@@ -17,33 +17,33 @@ function compile(packageOutPath, schemaDir, openapiDir, outDir) {
17
17
  packjson = fs_1.default.readFileSync(packageOutPath).toString();
18
18
  }
19
19
  const packageJson = JSON.parse(packjson);
20
- const vexgenScript = `vex -j ${schemaDir} -a ${openapiDir} -o ${outDir}`;
20
+ const vexgenScript = `vex -j ${schemaDir} -o ${outDir}`;
21
21
  if (packageJson.scripts.vexgen !== vexgenScript) {
22
22
  packageJson.scripts.vexgen = vexgenScript;
23
23
  writePackage = true;
24
- log_1.default.process(`package.json : Update script : vexgen > ${packageJson.scripts.vexgen}`);
24
+ logger_1.default.process(`package.json : Update script : vexgen > ${packageJson.scripts.vexgen}`);
25
25
  }
26
26
  if (!packageJson.scripts.build) {
27
27
  packageJson.scripts.build = "tsc -p .";
28
28
  writePackage = true;
29
- log_1.default.process(`package.json : Update script : build > ${packageJson.scripts.build}`);
29
+ logger_1.default.process(`package.json : Update script : build > ${packageJson.scripts.build}`);
30
30
  }
31
31
  if (!packageJson.scripts.dev) {
32
32
  packageJson.scripts.dev = `nodemon --watch src --exec ts-node ${outDir}/server.ts`;
33
33
  writePackage = true;
34
- log_1.default.process(`package.json : Update script : dev > ${packageJson.scripts.dev}`);
34
+ logger_1.default.process(`package.json : Update script : dev > ${packageJson.scripts.dev}`);
35
35
  }
36
36
  if (!packageJson.scripts.start) {
37
37
  packageJson.scripts.start = "node ./dist/server.js";
38
38
  writePackage = true;
39
- log_1.default.process(`package.json : Update script : start > ${packageJson.scripts.start}`);
39
+ logger_1.default.process(`package.json : Update script : start > ${packageJson.scripts.start}`);
40
40
  }
41
41
  if (writePackage) {
42
- log_1.default.writing(`Project : ${packageOutPath}`);
42
+ logger_1.default.writing(`Project : ${packageOutPath}`);
43
43
  fs_1.default.writeFileSync(packageOutPath, JSON.stringify(packageJson, null, 4));
44
44
  }
45
45
  else {
46
- log_1.default.info("package.json : No changes");
46
+ logger_1.default.info("package.json : No changes");
47
47
  }
48
48
  }
49
49
  exports.compile = compile;
@@ -0,0 +1,4 @@
1
+ import * as types from "../../types/types";
2
+ export declare function compile(options: {
3
+ compilerOptions: types.compilerOptions;
4
+ }): string;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.compile = void 0;
7
+ const common_1 = __importDefault(require("./../../utils/common"));
8
+ function loginHtml(providers) {
9
+ let html = "<p> login with : </p>";
10
+ providers.forEach((pp) => {
11
+ html += `<a href="\${process.env.APP_HOST}:\${process.env.APP_PORT}/auth/${pp}">${pp}</a>`;
12
+ });
13
+ return `\`${html}\``;
14
+ }
15
+ function compile(options) {
16
+ const providers = common_1.default.isUseOAuth(options.compilerOptions);
17
+ return `${options.compilerOptions.headerComment}
18
+ import { Router } from 'express';
19
+ import util from 'util';
20
+
21
+ export default class OAuthRouter{
22
+
23
+ public router: Router = Router();
24
+ private loginHtml = ${loginHtml(providers)};
25
+
26
+ constructor() {}
27
+
28
+ public initRoutes() {
29
+
30
+ this.router.get('/login', (req, res) => {
31
+ res.send(this.loginHtml);
32
+ });
33
+
34
+ this.router.get('/profile', (req, res) => {
35
+ if (req.isAuthenticated()) {
36
+ res.send(\`<p>Session Data</p><pre>\${util.inspect(req.user, undefined, null)}</pre>\`);
37
+ }
38
+ else {
39
+ res.redirect('/login');
40
+ };
41
+ });
42
+ }
43
+
44
+ }`;
45
+ }
46
+ exports.compile = compile;
@@ -5,7 +5,7 @@ export declare function compile(options: {
5
5
  interfaceName: string;
6
6
  controllerPath: string;
7
7
  }[];
8
- routesOutPath: string;
8
+ routesDir: string;
9
9
  openapiFile: string;
10
10
  compilerOptions: types.compilerOptions;
11
11
  }): void;
@@ -1,4 +1,27 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
2
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
27
  };
@@ -6,13 +29,26 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
29
  exports.compile = void 0;
7
30
  const fs_1 = __importDefault(require("fs"));
8
31
  const routes_template_1 = __importDefault(require("./routes.template"));
9
- const log_1 = __importDefault(require("../utils/log"));
32
+ const routesOAuthGen = __importStar(require("./routes/oauth.generator"));
33
+ const utils = __importStar(require("../utils/common"));
34
+ const logger_1 = __importDefault(require("../utils/logger"));
10
35
  function compile(options) {
11
- log_1.default.writing(`Router : ${options.routesOutPath}`);
12
- fs_1.default.writeFileSync(options.routesOutPath, (0, routes_template_1.default)({
36
+ const routesApiOutPath = `${options.routesDir}/ApiRouter.gen.ts`;
37
+ const routesOAuthOutPath = `${options.routesDir}/OAuthRouter.gen.ts`;
38
+ const routesSwaggerOutPath = `${options.routesDir}/SwaggerRouter.gen.ts`;
39
+ logger_1.default.writing(`Router : ${routesApiOutPath}`);
40
+ fs_1.default.writeFileSync(routesApiOutPath, (0, routes_template_1.default)({
13
41
  routes: options.routesArr,
14
42
  openapiFile: options.openapiFile,
15
43
  compilerOptions: options.compilerOptions,
16
44
  }));
45
+ if (utils.isUseOAuth(options.compilerOptions).length > 0) {
46
+ fs_1.default.writeFileSync(routesOAuthOutPath, routesOAuthGen.compile({
47
+ compilerOptions: options.compilerOptions || utils.defaultCompilerOptions
48
+ }));
49
+ }
50
+ if (options.compilerOptions.enableSwagger) {
51
+ fs_1.default.copyFileSync(`${__dirname}/../templates/routes/swagger.gen.ts`, routesSwaggerOutPath);
52
+ }
17
53
  }
18
54
  exports.compile = compile;