very-express 0.1.1 → 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 (38) 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 +9 -7
  7. package/dist/generators/controllers.generator.js +16 -19
  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/logger.gen.ts +23 -0
  32. package/dist/types/types.d.ts +13 -4
  33. package/dist/utils/common.d.ts +3 -1
  34. package/dist/utils/common.js +26 -11
  35. package/dist/utils/logger.d.ts +13 -0
  36. package/dist/utils/logger.js +31 -0
  37. package/package.json +3 -3
  38. package/vex.config.json +10 -2
@@ -1,29 +1,5 @@
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
- };
25
2
  Object.defineProperty(exports, "__esModule", { value: true });
26
- const utils = __importStar(require("../utils/common"));
27
3
  function routesTemplate(templateOptions) {
28
4
  var _a;
29
5
  if (!templateOptions.compilerOptions.headerComment) {
@@ -37,28 +13,31 @@ function routesTemplate(templateOptions) {
37
13
  const headerComment = ((_a = templateOptions.compilerOptions) === null || _a === void 0 ? void 0 : _a.headerComment) || "// generated files by very-express";
38
14
  let template = templateOptions.template || `{{headerComment}}
39
15
  import { Router } from 'express';
40
- import swaggerUi, { JsonObject } from 'swagger-ui-express';
41
16
  import { loadYaml } from '../utils/common.gen';
42
17
 
43
18
  {{importRoutes}}
44
19
 
45
- const router :Router = Router();
20
+ export default class ApiRouter{
21
+
22
+ public router: Router = Router();
23
+
24
+ constructor() {}
46
25
 
47
- {{openapiRoute}}
26
+ public initRoutes() {
48
27
 
49
- {{useRoutes}}
28
+ {{useRoutes}}
29
+
30
+ }
50
31
 
51
- export default router;`;
52
- const openapiPath = utils.relativePath(templateOptions.compilerOptions.rootDir, templateOptions.compilerOptions.openapiDir) + (templateOptions.openapiFile || "/openapi.gen.yaml");
32
+ }`;
53
33
  let importRoutes = "";
54
34
  let useRoutes = "";
55
35
  templateOptions === null || templateOptions === void 0 ? void 0 : templateOptions.routes.forEach((obj) => {
56
36
  importRoutes += `import ${obj.interfaceName}Controller from '${obj.controllerPath}';\n`;
57
- useRoutes += `router.use('${obj.route}', ${obj.interfaceName}Controller);\n`;
37
+ useRoutes += `this.router.use('${obj.route}', ${obj.interfaceName}Controller);\n`;
58
38
  });
59
39
  template = template.replace(/{{headerComment}}/g, headerComment);
60
40
  template = template.replace(/{{importRoutes}}/g, importRoutes);
61
- template = template.replace(/{{openapiRoute}}/g, enableOpenApi ? `router.use('/api', swaggerUi.serve, swaggerUi.setup(loadYaml('./${openapiPath}') as JsonObject));` : "");
62
41
  template = template.replace(/{{useRoutes}}/g, useRoutes);
63
42
  return template;
64
43
  }
@@ -1,2 +1,2 @@
1
1
  import * as types from "../types/types";
2
- export declare function compile(options: types.compilerOptions): void;
2
+ export declare function compile(compilerOptions: types.compilerOptions): void;
@@ -7,26 +7,23 @@ exports.compile = void 0;
7
7
  const fs_1 = __importDefault(require("fs"));
8
8
  const server_template_1 = __importDefault(require("./server.template"));
9
9
  const packageJson_generator_1 = __importDefault(require("./packageJson.generator"));
10
- const log_1 = __importDefault(require("../utils/log"));
11
- function compile(options) {
12
- const serverOutPath = options.srcDir + "/server.ts";
13
- const packageOutPath = options.rootDir + "/package.json";
14
- const envOutPath = options.rootDir + "/.env";
15
- const tsconfigOutPath = options.rootDir + "/tsconfig.json";
16
- if (!fs_1.default.existsSync(serverOutPath)) {
17
- log_1.default.writing(`Server : ${serverOutPath}`);
18
- fs_1.default.writeFileSync(serverOutPath, (0, server_template_1.default)({
19
- options: options,
20
- }));
21
- }
10
+ const logger_1 = __importDefault(require("../utils/logger"));
11
+ function compile(compilerOptions) {
12
+ const serverOutPath = compilerOptions.srcDir + "/server.gen.ts";
13
+ const packageOutPath = compilerOptions.rootDir + "/package.json";
14
+ const envOutPath = compilerOptions.rootDir + "/.env";
15
+ const tsconfigOutPath = compilerOptions.rootDir + "/tsconfig.json";
16
+ fs_1.default.writeFileSync(serverOutPath, (0, server_template_1.default)({
17
+ compilerOptions: compilerOptions,
18
+ }));
22
19
  if (!fs_1.default.existsSync(envOutPath)) {
23
- log_1.default.writing(`Project : ${envOutPath}`);
20
+ logger_1.default.writing(`Project : ${envOutPath}`);
24
21
  fs_1.default.copyFileSync(__dirname + "/../templates/root/.env", envOutPath);
25
22
  }
26
23
  if (!fs_1.default.existsSync(tsconfigOutPath)) {
27
- log_1.default.writing(`Project : ${tsconfigOutPath}`);
24
+ logger_1.default.writing(`Project : ${tsconfigOutPath}`);
28
25
  fs_1.default.copyFileSync(__dirname + "/../templates/root/tsconfig.json", tsconfigOutPath);
29
26
  }
30
- packageJson_generator_1.default.compile(packageOutPath, options.jsonSchemaDir, options.openapiDir, options.rootDir);
27
+ packageJson_generator_1.default.compile(packageOutPath, compilerOptions.jsonSchemaDir, compilerOptions.rootDir);
31
28
  }
32
29
  exports.compile = compile;
@@ -1,5 +1,5 @@
1
1
  import * as types from "../types/types";
2
- export default function serverTemplate(templateOptions: {
2
+ export default function serverTemplate(options: {
3
+ compilerOptions: types.compilerOptions;
3
4
  template?: string;
4
- options?: types.compilerOptions;
5
5
  }): string;
@@ -1,33 +1,129 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- function serverTemplate(templateOptions) {
6
+ const common_1 = __importDefault(require("./../utils/common"));
7
+ const importExpressSession = "import session from 'express-session';";
8
+ const importPassportGoogle = "import PassportGoogle from \"./plugins/PassportGoogle.gen\"";
9
+ const importSwaggerRouter = "import SwaggerRouter from './routes/SwaggerRouter.gen';";
10
+ const importOAuthRouter = "import OAuthRouter from './routes/OAuthRouter.gen';";
11
+ const ConfigExpressSession = `
12
+ const expressSessionConfig = {
13
+ secret: 'your session secret',
14
+ resave: false,
15
+ saveUninitialized: false
16
+ }`;
17
+ const ConfigSwaggerRouter = "const SwaggerRoute = new SwaggerRouter(); SwaggerRoute.initRoutes();";
18
+ const ConfigOAuthRouter = "const OAuthRoute = new OAuthRouter(); OAuthRoute.initRoutes();";
19
+ const ConfigPassportGoogle = `
20
+ const OAuthGoogle = new PassportGoogle({
21
+ strategyConfig: {
22
+ // @ts-ignore
23
+ verify: (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any) => void) => {
24
+ return done(null, profile);
25
+ }
26
+ }
27
+ });`;
28
+ const UseSession = "app.use(session(expressSessionConfig));";
29
+ const UsePassportGoogle = `
30
+ await OAuthGoogle.passportSerializeUser();
31
+ app.use(OAuthGoogle.passport.initialize());
32
+ app.use(OAuthGoogle.passport.session());`;
33
+ const UseOAuthRouter = "app.use(OAuthRoute.router);";
34
+ const UseSwaggerRouter = "app.use(SwaggerRoute.router);";
35
+ const UseOAuthGoogleRouter = "app.use(OAuthGoogle.router);";
36
+ function serverTemplate(options) {
4
37
  var _a;
5
- const headerComment = ((_a = templateOptions.options) === null || _a === void 0 ? void 0 : _a.headerComment) || "// generated files by very-express";
6
- let template = templateOptions.template || `{{headerComment}}
38
+ const headerComment = ((_a = options.compilerOptions) === null || _a === void 0 ? void 0 : _a.headerComment) || "// generated files by very-express";
39
+ let template = options.template || `{{headerComment}}
7
40
 
8
- import dotenv from 'dotenv';
9
41
  import express from 'express';
42
+ import dotenv from 'dotenv';
10
43
  import helmet from 'helmet';
11
- import routesGenerated from './routes/routes.gen';
12
44
 
13
- dotenv.config();
45
+ import mongoConn from './services/mongoConn.gen';
46
+ import log from './utils/logger.gen';
47
+
48
+ import ApiRouter from './routes/ApiRouter.gen';
49
+ {{Import}}
14
50
 
15
- const app = express();
16
- app.disable("x-powered-by");
17
- app.use(express.json());
18
51
 
19
- app.use(routesGenerated);
52
+ /**
53
+ * Configure
54
+ */
55
+ dotenv.config();
20
56
 
21
- app.use(helmet({
57
+ const helmetConfig = {
22
58
  xPoweredBy: false,
23
59
  xDnsPrefetchControl: { allow: false },
24
- }));
60
+ };
61
+
62
+ const ApiRoute = new ApiRouter(); ApiRoute.initRoutes();
63
+ {{Config}}
64
+
65
+
66
+ /**
67
+ * App
68
+ */
69
+ async function main(): Promise<void> {
70
+
71
+ const app = express();
72
+ app.disable("x-powered-by");
73
+ app.use(express.json());
74
+ app.use(helmet(helmetConfig));
75
+
76
+ // UsePlugins
77
+ {{AppUse}}
78
+
79
+ // Routes
80
+ {{AppRouter}}
81
+
82
+ app.use(ApiRoute.router);
83
+
84
+ app.get('/', (req, res) => {
85
+ res.send('Hello World');
86
+ });
87
+
88
+ app.listen(3000, () => {
89
+ if(!process.env.MONGODB_URI) throw new Error('MONGODB_URI is not defined');
90
+ mongoConn.connect(process.env.MONGODB_URI);
91
+ log.ok(\`Server is running on : \${process.env.APP_HOST}:\${process.env.APP_PORT}\`);
92
+ });
93
+
94
+ }
25
95
 
26
- app.listen(process.env.EXPRESS_PORT, () => {
27
- console.log('Server is running on port ' + process.env.EXPRESS_PORT );
28
- });
96
+ main();
29
97
  `;
98
+ const usedProvider = common_1.default.isUseOAuth(options.compilerOptions);
99
+ const Import = [];
100
+ const Config = [];
101
+ const AppUse = [];
102
+ const AppRoute = [];
103
+ if (usedProvider.length > 0) {
104
+ Import.push(importExpressSession);
105
+ Config.push(ConfigExpressSession);
106
+ AppUse.push(UseSession);
107
+ if (options.compilerOptions.enableSwagger) {
108
+ Import.push(importSwaggerRouter);
109
+ Config.push(ConfigSwaggerRouter);
110
+ AppRoute.push(UseSwaggerRouter);
111
+ }
112
+ Import.push(importOAuthRouter);
113
+ Config.push(ConfigOAuthRouter);
114
+ AppRoute.push(UseOAuthRouter);
115
+ if (usedProvider.includes("google")) {
116
+ Import.push(importPassportGoogle);
117
+ Config.push(ConfigPassportGoogle);
118
+ AppUse.push(UsePassportGoogle);
119
+ AppRoute.push(UseOAuthGoogleRouter);
120
+ }
121
+ }
30
122
  template = template.replace(/{{headerComment}}/g, headerComment);
123
+ template = template.replace(/{{Import}}/g, Import.join("\n"));
124
+ template = template.replace(/{{Config}}/g, Config.join("\n"));
125
+ template = template.replace(/{{AppUse}}/g, AppUse.join("\n "));
126
+ template = template.replace(/{{AppRouter}}/g, AppRoute.join("\n "));
31
127
  return template;
32
128
  }
33
129
  exports.default = serverTemplate;
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  import * as types from "./types/types";
2
- export default function generate(options: types.compilerOptions): void;
2
+ export declare function generate(options: types.compilerOptions): void;
package/dist/index.js CHANGED
@@ -26,10 +26,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.generate = void 0;
29
30
  const fs_1 = __importDefault(require("fs"));
30
31
  const json2mongoose_1 = __importDefault(require("json2mongoose"));
31
32
  const openapiGen = __importStar(require("./generators/openapi.generator"));
32
- const log_1 = __importDefault(require("./utils/log"));
33
+ const logger_1 = __importDefault(require("./utils/logger"));
33
34
  const common_1 = __importDefault(require("./utils/common"));
34
35
  const controllerGen = __importStar(require("./generators/controllers.generator"));
35
36
  const routeGen = __importStar(require("./generators/routes.generator"));
@@ -43,10 +44,10 @@ function generate(options) {
43
44
  modelDir: `${options.srcDir}/models`,
44
45
  typeDir: `${options.srcDir}/types`,
45
46
  serviceDir: `${options.srcDir}/services`,
47
+ pluginDir: `${options.srcDir}/plugins`,
46
48
  utilsDir: `${options.srcDir}/utils`,
47
49
  };
48
50
  const openapiFile = "/openapi.gen.yaml";
49
- const openapipath = options.openapiDir + openapiFile;
50
51
  if (!fs_1.default.existsSync(options.rootDir)) {
51
52
  fs_1.default.mkdirSync(options.rootDir);
52
53
  }
@@ -61,26 +62,23 @@ function generate(options) {
61
62
  fs_1.default.mkdirSync(path);
62
63
  }
63
64
  });
64
- log_1.default.process(`Router : ${openapipath}`);
65
+ openapiGen.compile(openapiFile, options);
66
+ common_1.default.copyDir(`${__dirname}/templates/utils`, dir.utilsDir, true);
67
+ common_1.default.copyDir(`${__dirname}/templates/services`, dir.serviceDir, true);
68
+ common_1.default.copyDir(`${__dirname}/templates/plugins`, dir.pluginDir, true);
65
69
  const routeData = [];
66
70
  const files = fs_1.default.readdirSync(options.jsonSchemaDir);
67
71
  files.forEach((schemaFileName) => {
68
72
  const schemaPath = `${options.jsonSchemaDir}/${schemaFileName}`;
69
73
  try {
70
74
  if (!schemaFileName.endsWith(".json")) {
71
- log_1.default.warn(`Skipping Non Json File : ${schemaPath}`);
75
+ logger_1.default.warn(`Skipping Non Json File : ${schemaPath}`);
72
76
  return;
73
77
  }
74
78
  const jsonSchema = (0, jsonschemaFormat_1.formatJsonSchema)(schemaPath);
75
79
  const documentConfig = jsonSchema["x-documentConfig"];
76
- if (typeof jsonSchema.properties !== "object")
77
- log_1.default.error(`properties is invalid in ${schemaPath}`);
78
- if (!fs_1.default.existsSync(`${schemaPath}.nogen.ts`)) {
79
- json2mongoose_1.default.typesGen.compileFromFile(`${schemaPath}`, `${dir.typeDir}/${documentConfig.interfaceName}.gen.ts`, options || common_1.default.defaultCompilerOptions);
80
- }
81
- if (!fs_1.default.existsSync(`${schemaPath}Model.nogen.ts`)) {
82
- json2mongoose_1.default.modelsGen.compileFromFile(`${schemaPath}`, `${common_1.default.relativePath(dir.modelDir, dir.typeDir)}/${documentConfig.interfaceName}.gen`, `${dir.modelDir}/${documentConfig.interfaceName}Model.gen.ts`, options || common_1.default.defaultCompilerOptions);
83
- }
80
+ json2mongoose_1.default.typesGen.compileFromFile(`${schemaPath}`, `${dir.typeDir}/${documentConfig.interfaceName}.gen.ts`, options || common_1.default.defaultCompilerOptions);
81
+ json2mongoose_1.default.modelsGen.compileFromFile(`${schemaPath}`, `${common_1.default.relativePath(dir.modelDir, dir.typeDir)}/${documentConfig.interfaceName}.gen`, `${dir.modelDir}/${documentConfig.interfaceName}Model.gen.ts`, options || common_1.default.defaultCompilerOptions);
84
82
  routeData.push({
85
83
  route: `/${documentConfig.documentName}`,
86
84
  interfaceName: documentConfig.interfaceName,
@@ -88,17 +86,11 @@ function generate(options) {
88
86
  });
89
87
  }
90
88
  catch (err) {
91
- log_1.default.error(`Processing File : ${schemaPath}\n`, err);
89
+ logger_1.default.error(`Processing File : ${schemaPath}\n`, err);
92
90
  }
93
91
  });
94
- if (!fs_1.default.existsSync(options.openapiDir + "/openapi.nogen.yaml")) {
95
- openapiGen.compile({
96
- openapiOutFileName: openapiFile,
97
- compilerOptions: options || common_1.default.defaultCompilerOptions
98
- });
99
- }
100
- common_1.default.copyDir(`${options.openapiDir}`, options.rootDir + "/openapi");
101
- common_1.default.copyDir(`${__dirname}/templates/utils`, dir.utilsDir);
92
+ openapiGen.compile(openapiFile, options || common_1.default.defaultCompilerOptions);
93
+ common_1.default.copyDir(`${options.openapiDir}`, options.rootDir + "/openapi", true);
102
94
  controllerGen.compile({
103
95
  openapiFile: openapiFile,
104
96
  controllerOutDir: dir.controllerDir,
@@ -108,9 +100,9 @@ function generate(options) {
108
100
  routeGen.compile({
109
101
  routesArr: routeData,
110
102
  openapiFile: openapiFile,
111
- routesOutPath: `${dir.routeDir}/routes.gen.ts`,
103
+ routesDir: dir.routeDir,
112
104
  compilerOptions: options || common_1.default.defaultCompilerOptions
113
105
  });
114
106
  serverGen.compile(options);
115
107
  }
116
- exports.default = generate;
108
+ exports.generate = generate;
@@ -30,25 +30,28 @@ exports.formatJsonSchema = void 0;
30
30
  const fs_1 = __importDefault(require("fs"));
31
31
  const types = __importStar(require("../types/types"));
32
32
  const common = __importStar(require("../utils/common"));
33
- const log_1 = __importDefault(require("../utils/log"));
33
+ const logger_1 = __importDefault(require("../utils/logger"));
34
34
  function formatJsonSchema(jsonSchemaPath) {
35
35
  const jsonSchema = common.loadJsonSchema(jsonSchemaPath);
36
36
  if (jsonSchema == undefined) {
37
- log_1.default.error("formatJsonSchema : error at loadJsonSchema()");
37
+ logger_1.default.error("formatJsonSchema : error at loadJsonSchema()");
38
38
  }
39
39
  if (!jsonSchema["x-documentConfig"]) {
40
- log_1.default.error(`formatJsonSchema : x-documentConfig not found in ${jsonSchemaPath}`);
40
+ logger_1.default.error(`formatJsonSchema : x-documentConfig not found in ${jsonSchemaPath}`);
41
41
  }
42
42
  else if (!jsonSchema["x-documentConfig"].documentName) {
43
- log_1.default.error(`formatJsonSchema : x-documentConfig.documentName not found in ${jsonSchemaPath}`);
43
+ logger_1.default.error(`formatJsonSchema : x-documentConfig.documentName not found in ${jsonSchemaPath}`);
44
44
  }
45
45
  else if (!jsonSchema["x-documentConfig"].interfaceName) {
46
- log_1.default.error(`formatJsonSchema : x-documentConfig.interfaceName not found in ${jsonSchemaPath}`);
46
+ logger_1.default.error(`formatJsonSchema : x-documentConfig.interfaceName not found in ${jsonSchemaPath}`);
47
47
  }
48
48
  else if (!jsonSchema["x-documentConfig"].methods) {
49
- log_1.default.warn(`formatJsonSchema : x-documentConfig.methods is not found in ${jsonSchemaPath}, initialize all supported methods.`);
49
+ logger_1.default.warn(`formatJsonSchema : x-documentConfig.methods is not found in ${jsonSchemaPath}, supported methods added.`);
50
50
  jsonSchema["x-documentConfig"].methods = Object.assign([], types.schemaMethodArr);
51
51
  }
52
+ if (typeof jsonSchema.properties !== "object") {
53
+ logger_1.default.error(`properties is invalid in ${jsonSchemaPath}`);
54
+ }
52
55
  jsonSchema.required = getRequiredArrStr(jsonSchema, jsonSchemaPath);
53
56
  fs_1.default.writeFileSync(jsonSchemaPath, JSON.stringify(jsonSchema, null, 4));
54
57
  return jsonSchema;
@@ -70,7 +73,7 @@ function getRequiredArrStr(schema, jsonSchemaPath) {
70
73
  return undefined;
71
74
  }
72
75
  if (properties == undefined) {
73
- log_1.default.error(`formatJsonSchema > formatRequired : invalid "schema.properties" in ${jsonSchemaPath}`, schema);
76
+ logger_1.default.error(`formatJsonSchema > formatRequired : invalid "schema.properties" in ${jsonSchemaPath}`, schema);
74
77
  }
75
78
  else {
76
79
  Object.keys(properties).forEach((propKey) => {
@@ -0,0 +1,51 @@
1
+ {
2
+ "type": "object",
3
+ "x-documentConfig": {
4
+ "documentName": "user",
5
+ "interfaceName": "User",
6
+ "methods": [
7
+ "get",
8
+ "getList",
9
+ "post",
10
+ "patch"
11
+ ]
12
+ },
13
+ "properties": {
14
+ "_id": {
15
+ "type": "string",
16
+ "index": true
17
+ },
18
+ "authProvider": {
19
+ "type": "string"
20
+ },
21
+ "email": {
22
+ "type": "string",
23
+ "format": "email",
24
+ "index": true,
25
+ "required": true
26
+ },
27
+ "emailVerified": {
28
+ "type": "boolean",
29
+ "required": true,
30
+ "default": false
31
+ },
32
+ "authId": {
33
+ "type": "string",
34
+ "index": true
35
+ },
36
+ "name": {
37
+ "type": "string",
38
+ "maxLength": 64,
39
+ "required": true
40
+ },
41
+ "locale": {
42
+ "type": "string",
43
+ "maxLength": 8,
44
+ "required": true
45
+ },
46
+ "isActive": {
47
+ "type": "boolean",
48
+ "required": true
49
+ }
50
+ }
51
+ }
@@ -0,0 +1,64 @@
1
+ import { Router } from "express";
2
+ import passport, { PassportStatic, Profile } from "passport";
3
+ import { AuthenticateOptionsGoogle, Strategy as GoogleStrategy, StrategyOptions, VerifyCallback } from "passport-google-oauth20";
4
+ // import log from '../utils/logger.gen';
5
+
6
+ export type { Profile };
7
+
8
+ export interface passportGoogleConfig {
9
+ strategyConfig: {
10
+ options?: StrategyOptions,
11
+ verify: (accessToken: string, refreshToken: string, profile: Profile, done: VerifyCallback) => void
12
+ },
13
+ authenticateOptionsGoogle?: AuthenticateOptionsGoogle,
14
+ }
15
+
16
+ /** Provides a router and passport instance for Google OAuth */
17
+ export default class PassportGoogle {
18
+
19
+ private config: passportGoogleConfig;
20
+ public router: Router = Router();
21
+ public passport: PassportStatic = passport;
22
+
23
+ constructor(config: passportGoogleConfig ) {
24
+
25
+ this.config = config;
26
+
27
+ this.passport.use(new GoogleStrategy(
28
+ this.config.strategyConfig.options || {
29
+ clientID: process.env.OAUTH_GOOGLE_CLIENTID || "",
30
+ clientSecret: process.env.OAUTH_GOOGLE_CLIENTSECRET || "",
31
+ callbackURL: `${process.env.APP_HOST}:${process.env.APP_PORT}/auth/google/callback`,
32
+ },
33
+ this.config.strategyConfig.verify
34
+ ));
35
+
36
+ // redirect to google login
37
+ this.router.get("/auth/google",
38
+ this.passport.authenticate("google", this.config.authenticateOptionsGoogle || { scope: ["profile", "email"] })
39
+ );
40
+
41
+ // back from google login
42
+ this.router.get("/auth/google/callback",
43
+ this.passport.authenticate("google", { failureRedirect: "/login" }),
44
+ (req, res) => {
45
+ // res.send(`Hello, user <pre>${req.user}</pre>`);
46
+ res.redirect("/profile");
47
+ }
48
+ );
49
+ }
50
+
51
+ public async passportSerializeUser() {
52
+
53
+ await this.passport.serializeUser((user, done) => {
54
+ // log.info('passportGoogle().serializeUser', user)
55
+ done(null, user);
56
+ });
57
+
58
+ await this.passport.deserializeUser((id, done) => {
59
+ // log.info('passportGoogle().deserializeUser', id)
60
+ done(null, { id });
61
+ });
62
+ }
63
+
64
+ }
@@ -0,0 +1,33 @@
1
+ // import log from '../utils/logger.gen';
2
+ import { Profile } from "passport";
3
+ import { UserModel } from "../models/UserModel.gen";
4
+
5
+ interface IProfile extends Profile {
6
+ [key: string]: any;
7
+ }
8
+
9
+ export async function oauthVerify(accessToken: string, refreshToken: string, profile: IProfile, done: (error: any, user?: any) => void) : Promise<void> {
10
+
11
+ // find or create user
12
+ const existingUser = await UserModel.findOne({ email: profile.emails?.[0].value });
13
+
14
+ if( existingUser ){
15
+ // log.info('OAuthVerify ExistingUser');
16
+ return done(null, profile);
17
+ }
18
+ else {
19
+ // log.info('OAuthVerify NewUser');
20
+ const newUser = new UserModel({
21
+ authProvider: profile.provider,
22
+ email: profile.emails?.[0].value || "",
23
+ authId: profile.id,
24
+ name: profile.displayName,
25
+ familyName: profile.name?.familyName,
26
+ givenName: profile.name?.givenName,
27
+ isActive: true,
28
+ locale: profile._json?.locale,
29
+ });
30
+ newUser.save();
31
+ return done(null, profile);
32
+ }
33
+ }
@@ -1,2 +1,6 @@
1
- # veryExpress generated
2
- EXPRESS_PORT=3000
1
+ APP_HOST=http://localhost
2
+ APP_PORT=3000
3
+ MONGODB_URI=mongodb://localhost:27017/veryExpressDB
4
+
5
+ OAUTH_GOOGLE_CLIENTID=
6
+ OAUTH_GOOGLE_CLIENTSECRET=
@@ -3,8 +3,8 @@
3
3
  "scripts": {
4
4
  "vexgen": "vex",
5
5
  "build": "tsc -p .",
6
- "start": "node dist/server.js",
7
- "dev": "nodemon --exec ts-node src/server.ts"
6
+ "start": "node dist/server.gen.js",
7
+ "dev": "nodemon --exec ts-node src/server.gen.ts"
8
8
  },
9
9
  "dependencies": {
10
10
  "dotenv": "^16.3.1",
@@ -13,12 +13,13 @@
13
13
  "helmet": "^7.1.0",
14
14
  "js-yaml": "^4.1.0",
15
15
  "mongoose": "^8.0.3",
16
+ "mongo-ts-querystring": "^1.0.0",
16
17
  "nodemon": "^2.0.22",
17
18
  "passport": "^0.7.0",
18
19
  "passport-google-oauth20": "^2.0.0",
19
20
  "swagger-ui-express": "^5.0.0"
20
- },
21
- "devDependencies": {
21
+ },
22
+ "devDependencies": {
22
23
  "@types/express": "^4.17.21",
23
24
  "@types/js-yaml": "^4.0.9",
24
25
  "@types/node": "^20.10.5",
@@ -27,5 +28,5 @@
27
28
  "@types/swagger-ui-express": "^4.1.6",
28
29
  "ts-node": "^10.9.2",
29
30
  "typescript": "^5.3.3"
30
- }
31
+ }
31
32
  }
@@ -0,0 +1,17 @@
1
+ import { Router } from "express";
2
+ import swaggerUi, { JsonObject } from "swagger-ui-express";
3
+ import { loadYaml } from "../utils/common.gen";
4
+
5
+
6
+ export default class SwaggerRouter{
7
+
8
+ public router: Router = Router();
9
+
10
+ constructor() {}
11
+
12
+ public initRoutes() {
13
+ this.router.use("/api", swaggerUi.serve, swaggerUi.setup(loadYaml("./openapi/openapi.gen.yaml") as JsonObject));
14
+
15
+ }
16
+
17
+ }
@@ -0,0 +1,25 @@
1
+ import mongoose from "mongoose";
2
+ import log from "../utils/logger.gen";
3
+
4
+ export function connect(mongoUrl:string): mongoose.Connection {
5
+ mongoose.connect(mongoUrl, {
6
+ autoCreate: true,
7
+ });
8
+
9
+ mongoose.connection.on("open", () => {
10
+ log.ok("MongoDB Connection open : " + mongoUrl);
11
+ });
12
+
13
+ mongoose.connection.on("error", (err: any) => {
14
+ log.error("MongoDB Connection error:", err.message, err);
15
+ });
16
+
17
+ return mongoose.connection;
18
+ }
19
+
20
+
21
+ const mongo = {
22
+ connect,
23
+ };
24
+
25
+ export default mongo;