very-express 0.4.10 → 0.4.11

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 (53) hide show
  1. package/README.md +8 -0
  2. package/dist/index.js +1144 -734
  3. package/dist/templates/_controller/_ControllerFactory.ts +7 -0
  4. package/dist/templates/_controllers/_ControllerFactory.ts +9 -0
  5. package/dist/templates/_plugins/PassportGoogle.ts +3 -6
  6. package/dist/templates/_services/VexDbConnector.ts +3 -3
  7. package/dist/templates/_utils/index.ts +2 -0
  8. package/dist/templates/_utils/logger.ts +8 -3
  9. package/dist/templates/_utils/validator.ts +7 -0
  10. package/dist/templates/root/README.md +33 -0
  11. package/docs/developmentNote.md +11 -4
  12. package/docs/vexJsonSchema.md +30 -16
  13. package/package.json +9 -15
  14. package/scripts/build.js +14 -0
  15. package/scripts/copyTsTemplates.js +24 -0
  16. package/dist/_plugins/PassportGoogle.ts +0 -87
  17. package/dist/_plugins/oauthVerify.ts +0 -39
  18. package/dist/_roles/_RoleFactory.ts +0 -22
  19. package/dist/_services/VexDbConnector.ts +0 -70
  20. package/dist/_types/responseMsg.ts +0 -20
  21. package/dist/_utils/common.ts +0 -53
  22. package/dist/_utils/index.ts +0 -11
  23. package/dist/_utils/logger.ts +0 -50
  24. package/dist/_utils/response.ts +0 -27
  25. package/dist/cli.d.ts +0 -1
  26. package/dist/generators/app/openapi.generator.d.ts +0 -3
  27. package/dist/generators/app/server.generator.d.ts +0 -2
  28. package/dist/generators/app/server.template.d.ts +0 -5
  29. package/dist/generators/controller/controller.template.d.ts +0 -14
  30. package/dist/generators/controller/controllers.generator.d.ts +0 -7
  31. package/dist/generators/index.d.ts +0 -9
  32. package/dist/generators/middlewares/RBACmiddleware.generator.d.ts +0 -6
  33. package/dist/generators/middlewares/RBACmiddlewares.template.d.ts +0 -6
  34. package/dist/generators/project/packageJson.generator.d.ts +0 -6
  35. package/dist/generators/project/userSchema.generator.d.ts +0 -4
  36. package/dist/generators/role/role.generator.d.ts +0 -8
  37. package/dist/generators/role/role.template.d.ts +0 -8
  38. package/dist/generators/routes/oauth.generator.d.ts +0 -2
  39. package/dist/generators/routes/routes.generator.d.ts +0 -11
  40. package/dist/generators/routes/routes.template.d.ts +0 -11
  41. package/dist/generators/routes/swagger.generator.d.ts +0 -2
  42. package/dist/index.d.ts +0 -2
  43. package/dist/preprocess/jsonschemaFormat.d.ts +0 -2
  44. package/dist/preprocess/roleSetupFile.d.ts +0 -9
  45. package/dist/templates/_roles/_RoleFactory.d.ts +0 -10
  46. package/dist/types/openapi.d.ts +0 -108
  47. package/dist/types/types.d.ts +0 -75
  48. package/dist/utils/common.d.ts +0 -13
  49. package/dist/utils/configChecker.d.ts +0 -6
  50. package/dist/utils/generator.d.ts +0 -12
  51. package/dist/utils/index.d.ts +0 -30
  52. package/dist/utils/jsonSchema.d.ts +0 -14
  53. package/dist/utils/logger.d.ts +0 -13
@@ -0,0 +1,7 @@
1
+ export default class _ControllerFactory {
2
+
3
+ protected isObjectId(id: string): boolean {
4
+ return /^[0-9a-fA-F]{24}$/.test(id);
5
+ }
6
+
7
+ }
@@ -0,0 +1,9 @@
1
+ export class _ControllerFactory {
2
+
3
+ constructor() {}
4
+
5
+ protected isObjectId(id: string): boolean {
6
+ return /^[0-9a-fA-F]{24}$/.test(id);
7
+ }
8
+
9
+ }
@@ -3,7 +3,6 @@
3
3
  import { Router } from "express";
4
4
  import passport, { PassportStatic, Profile } from "passport";
5
5
  import { AuthenticateOptionsGoogle, Strategy as GoogleStrategy, StrategyOptions, VerifyCallback } from "passport-google-oauth20";
6
- import log from "./../../system/_utils/logger.gen";
7
6
  import { UserModel } from "./../_models/UserModel.gen";
8
7
 
9
8
  export type { Profile };
@@ -52,10 +51,9 @@ export default class PassportGoogle {
52
51
 
53
52
  public passportSerializeUser() {
54
53
  this.passport.serializeUser(async (user, done) => {
55
- log.info("passportGoogle().serializeUser", user);
56
- // Here, you can choose what data to store in the session.
57
- // This data will be used in `deserializeUser` to retrieve the full user object.
58
- // This is typically just the user's ID.
54
+ // you can decide what data to store in the session here.
55
+ // this data will be used in `deserializeUser` to retrieve the full user object.
56
+ // ussually just user's id.
59
57
 
60
58
  // store role in session for access control
61
59
  const DbUser = await UserModel.findById(user);
@@ -71,7 +69,6 @@ export default class PassportGoogle {
71
69
 
72
70
  public async passportDeserializeUser() {
73
71
  this.passport.deserializeUser(async (id, done) => {
74
- log.info("passportGoogle().deserializeUser", id);
75
72
 
76
73
  const user = await UserModel.findById(id);
77
74
  if (user) {
@@ -19,7 +19,7 @@ export default class VexDbConnector {
19
19
 
20
20
  connectMongo() : mongoose.Connection | void {
21
21
  if ( !this.mongoUrl ){
22
- vex.log.error(`VexDbConnector : MongoUrl is not invalid "${this.mongoUrl}"`);
22
+ vex.log.error("VexDbConnector : MongoUrl is not invalid");
23
23
  return;
24
24
  }
25
25
  /**
@@ -39,11 +39,11 @@ export default class VexDbConnector {
39
39
  connectWithRetry(10);
40
40
 
41
41
  mongoose.connection.on("open", () => {
42
- vex.log.infoMongo("MongoDB Connection open : " + this.mongoUrl);
42
+ vex.log.infoMongo("MongoDB Connection open");
43
43
  });
44
44
 
45
45
  mongoose.connection.on("error", (err: any) => {
46
- vex.log.errorMongo("MongoDB Connection error:", err.message, err);
46
+ vex.log.errorMongo("MongoDB Connection error: ", err.message, err);
47
47
  });
48
48
 
49
49
  return mongoose.connection;
@@ -1,11 +1,13 @@
1
1
  import logger from "./logger.gen";
2
2
  import response from "./response.gen";
3
+ import validator from "./validator.gen";
3
4
  import { responseMsg } from "./../_types/responseMsg.gen";
4
5
  import common from "./common.gen";
5
6
 
6
7
  export default {
7
8
  log : logger,
8
9
  response,
10
+ validator,
9
11
  responseMsg : responseMsg ,
10
12
  common
11
13
  };
@@ -15,17 +15,21 @@ export function warn(msg: any, ...optionalParams: any[]): void {
15
15
  }
16
16
 
17
17
  export function error(msg: any, ...optionalParams: any[]): never {
18
- console.log("\x1b[41m%s\x1b[0m", "[ERROR]", msg, optionalParams.length > 0 ? optionalParams : "");
18
+ errorNoExit(msg, optionalParams);
19
19
  process.exit(1);
20
20
  }
21
21
 
22
+ export function errorNoExit(msg: any, ...optionalParams: any[]): void {
23
+ console.log("\x1b[41m%s\x1b[0m", "[ERROR]", msg, optionalParams.length > 0 ? optionalParams : "");
24
+ }
25
+
22
26
  // wrapper
23
27
  export function infoMongo(msg: any, ...optionalParams: any[]): void {
24
28
  info("[MONGO]", msg, optionalParams);
25
29
  }
26
30
 
27
- export function errorMongo(msg: any, ...optionalParams: any[]): never {
28
- error("[MONGO]", msg, optionalParams);
31
+ export function errorMongo(msg: any, ...optionalParams: any[]): void {
32
+ errorNoExit("[MONGO]", msg, optionalParams);
29
33
  }
30
34
 
31
35
  export function infoSql(msg: any, ...optionalParams: any[]): void {
@@ -42,6 +46,7 @@ export default {
42
46
  info,
43
47
  warn,
44
48
  error,
49
+ errorNoExit,
45
50
 
46
51
  infoMongo,
47
52
  errorMongo,
@@ -0,0 +1,7 @@
1
+ export function checkObjectId(value:string): boolean {
2
+ return /^[0-9a-fA-F]{24}$/.test(value);
3
+ }
4
+
5
+ export default {
6
+ checkObjectId
7
+ };
@@ -0,0 +1,33 @@
1
+ # This app is generated by [VeryExpress](https://github.com/Justin26l/VeryExpress)
2
+
3
+
4
+ # Quick Start
5
+
6
+ 1. check configuration file **vex.config.json** under your project root directory.
7
+ [vex.config.json](./vex.config.json)
8
+
9
+ 2. generate the app with your vex.config settings.
10
+ *Note : every db schema changes require to regenerate app.
11
+ `vex`
12
+ 3. you should saw a express typescript app being generated.
13
+ ```
14
+ ├── src/
15
+ │ └── ...
16
+ ├── package.json
17
+ ├── tsconfig.json
18
+ ├── vex.config.json
19
+ ├── .env
20
+ └── ...
21
+ ```
22
+
23
+ 4. start the generated express app.
24
+ ```
25
+ npm i
26
+ npm build
27
+ npm run start
28
+ ```
29
+
30
+ # Resource
31
+ - [Documents](https://github.com/Justin26l/VeryExpress/blob/main/README.md)
32
+
33
+ - [Discord](https://discord.gg/PZGMzDp7)
@@ -9,8 +9,15 @@
9
9
  we do not use ts-node in development due to file structure of the project,
10
10
  you can refer to [package.json](./../package.json) "dev" script to know how to run the project in development.
11
11
 
12
- 2. **@vercel/ncc**
13
- we use this package to compile the project into single file.
14
- the project must be compiled to run as expected.
12
+ 2. **Esbuild**
13
+ the project require to compile into bundle to run.
14
+ due to the single file design, working directory of the project will always be at "dist/".
15
+ refer to [package.json](./../package.json) `scripts > compile`.
15
16
 
16
- due to the single file design, working directory of the project will always be at "dist/".
17
+ 3. **File Generate Template**
18
+ if there is any function calling pass by object need to be write in file output,
19
+ use syntax: `FUNC{{ <myFunc(){...}> }}`.
20
+ refer to :
21
+ 1. [controller custom validatior](./../src/generators/controller/controllers.generator.ts#L<202>)
22
+ 2. [controller template return](./../src/generators/controller/controller.template.ts#L<246>)
23
+ 3. [template formatter function](./../src/utils/template.ts#L<6>)
@@ -1,26 +1,33 @@
1
- # Define Json Schema
2
- this document tell how very express process the json schema.
3
- ### x-documentConfig:
1
+ # Define Json Schema for VeryExpress
2
+
3
+ ## x-documentConfig:
4
4
 
5
5
  | Fields | Data Type | Options | Description |
6
6
  | - | - | - | - |
7
- | documentName | `string` | - | auto generated as file name. used to name **Collection**, **TS Interface**, **ODM Model** etc. |
8
- | methods | `array<string>` | `get`, `post`, `put`, `patch`, `delete` | array of **REST API Method** to be generated. |
7
+ | documentName | `string` | - | auto generated using file name. used to name **Collection**, **TS Interface**, **ODM Model** etc. |
8
+ | methods | `array<string>` | `get`, `post`, `put`, `patch`, `delete` | array of **REST API Method** to be enable. |
9
9
 
10
10
 
11
- ### Properties Mandatory Value:
11
+ ## Properties Definition:
12
12
 
13
- | Fields | Data Type | Required | Description |
14
- | - | - | - | - |
15
- | type | `string` | true | [JsonSchema's type field](https://json-schema.org/understanding-json-schema/reference/type) |
16
- | required | `boolean` | false | generated api will check field must be defined. |
17
- | x-foreignKey | `string` | false | `documentName` from other JsonSchema, plan to implemented on [v0.5.0](./RoadMap/v0-5-0.md) |
18
- <!-- | format | `string` | false | veryExpress did not handle this field | -->
13
+ | Fields | Data Type | Required | options | Description |
14
+ | - | - | - | - | - |
15
+ | type | `string` | true | - | [JsonSchema's type field](https://json-schema.org/understanding-json-schema/reference/type) |
16
+ | required | `boolean` | false | - | rest api's validator will check value cannot be falsy / undefined. |
17
+ | x-vexData | `string` | false | `primaryKey`, `role` | determine veryExpress generation process. |
18
+ | x-foreignKey | - | - | - | `documentName` from other JsonSchema, auto index. plan to implemented on [v0.5.0](./RoadMap/v0-5-0.md) |
19
+ <!-- | format | `string` | false | - | veryExpress did not handle this field | -->
20
+
21
+ ### System Fields
22
+ which mean there field properties is not changable.
23
+ - `_id` : if defined in schema, will auto set as `"index": true`, `"x-vexData": "ObjectId"`.
19
24
 
25
+
26
+ #### Example :
20
27
  ```JSON
21
28
  {
22
29
  "x-documentConfig": {
23
- "documentName": "user", // auto generate as file name
30
+ "documentName": "user", // auto generated using name
24
31
  "methods": [
25
32
  "get",
26
33
  "post",
@@ -30,10 +37,17 @@ this document tell how very express process the json schema.
30
37
  ]
31
38
  },
32
39
  "properties": {
33
- "invoiceId": {
40
+ "_id": {
41
+ "type": "string",
42
+ "index": true,
43
+ "x-vexData": "ObjectId"
44
+ },
45
+ "username": {
46
+ "type": "string"
47
+ },
48
+ "invoice_id": {
34
49
  "type": "string",
35
- "format": "uuid",
36
- "required": false,
50
+ "required": true,
37
51
  "x-foreignKey": "invoice"
38
52
  }
39
53
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "very-express",
3
- "version": "0.4.10",
3
+ "version": "0.4.11",
4
4
  "description": "based on json schema and openapi, generate Express RestApi server with mongoDb ",
5
5
  "author": "justin26l",
6
6
  "license": "MIT",
@@ -11,10 +11,9 @@
11
11
  "scripts": {
12
12
  "start": "node ./dist/index.js",
13
13
  "dev": "npm run compile && npm run start",
14
- "build": "npm run lint && npm run compile && npm run minify",
14
+ "build": "npm run lint && npm run compile",
15
15
  "lint": "eslint ./src --ext .ts --fix",
16
- "compile": "ncc build ./src/cli.ts -o dist && node ./src/copyTsTemplates.js",
17
- "minify": "uglifyjs ./dist/index.js -c -m -o ./dist/index.js"
16
+ "compile": "node ./scripts/build.js && node ./scripts/copyTsTemplates.js"
18
17
  },
19
18
  "keywords": [
20
19
  "jsonSchema",
@@ -28,15 +27,6 @@
28
27
  "type": "git",
29
28
  "url": "git+https://github.com/Justin26l/VeryExpress.git"
30
29
  },
31
- "dependencies": {
32
- "@vercel/ncc": "^0.38.1",
33
- "express-session": "^1.17.3",
34
- "js-yaml": "4.1.0",
35
- "json-schema-to-openapi-schema": "^0.4.0",
36
- "json-schema-to-typescript": "^13.1.1",
37
- "json2mongoose": "^0.3.0",
38
- "minimist": "^1.2.8"
39
- },
40
30
  "devDependencies": {
41
31
  "@types/express": "^4.17.21",
42
32
  "@types/express-session": "^1.17.10",
@@ -49,17 +39,21 @@
49
39
  "@typescript-eslint/eslint-plugin": "^6.18.1",
50
40
  "@typescript-eslint/parser": "^6.18.1",
51
41
  "dotenv": "^16.3.1",
42
+ "esbuild": "0.23.0",
52
43
  "eslint": "^8.56.0",
53
44
  "express": "^4.18.2",
45
+ "express-session": "^1.17.3",
54
46
  "express-validator": "^7.0.1",
55
47
  "helmet": "^7.1.0",
56
48
  "js-yaml": "^4.1.0",
57
49
  "json-schema-to-openapi-schema": "^0.4.0",
50
+ "json-schema-to-typescript": "^13.1.1",
51
+ "json2mongoose": "^0.3.5",
52
+ "minimist": "^1.2.8",
58
53
  "passport": "^0.7.0",
59
54
  "passport-google-oauth20": "^2.0.0",
60
55
  "swagger-ui-express": "^5.0.0",
61
56
  "ts-node": "^10.9.2",
62
- "typescript": "^5.3.3",
63
- "uglify-js": "^3.17.4"
57
+ "typescript": "^5.3.3"
64
58
  }
65
59
  }
@@ -0,0 +1,14 @@
1
+ const esbuild = require('esbuild');
2
+
3
+ esbuild.build({
4
+ entryPoints: ['./src/cli.ts'], // Your main file
5
+ bundle: true, // Bundle all dependencies
6
+ platform: 'node', // Specify the platform
7
+ target: 'es2016', // Target Node version, adjust as needed
8
+ minify: true, // Minify the output
9
+ tsconfig: './tsconfig.json', // Your tsconfig file
10
+ outfile: './dist/index.js', // Output file
11
+ }).catch((e) => {
12
+ console.error(e);
13
+ process.exit(1);
14
+ });
@@ -0,0 +1,24 @@
1
+ // copy dir src/templates/utils to dist/templates/utils
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+
5
+ /**
6
+ * to copy template files into tsc output dir (dist)
7
+ */
8
+ function copyDir (src, destination) {
9
+ if (!fs.existsSync(destination)) {
10
+ fs.mkdirSync(destination);
11
+ }
12
+ fs.readdirSync(src).forEach((file) => {
13
+ const srcPath = path.join(src, file);
14
+ const destPath = path.join(destination, file);
15
+ const stat = fs.statSync(srcPath);
16
+ if (stat.isFile()) {
17
+ fs.writeFileSync(destPath, fs.readFileSync(srcPath));
18
+ } else if (stat.isDirectory()) {
19
+ copyDir(srcPath, destPath);
20
+ }
21
+ });
22
+ }
23
+
24
+ copyDir('src/templates', 'dist/templates');
@@ -1,87 +0,0 @@
1
- // {{headerComment}}
2
-
3
- import { Router } from "express";
4
- import passport, { PassportStatic, Profile } from "passport";
5
- import { AuthenticateOptionsGoogle, Strategy as GoogleStrategy, StrategyOptions, VerifyCallback } from "passport-google-oauth20";
6
- import log from "./../../system/_utils/logger.gen";
7
- import { UserModel } from "./../_models/UserModel.gen";
8
-
9
- export type { Profile };
10
-
11
- export interface passportGoogleConfig {
12
- strategyConfig: {
13
- options?: StrategyOptions,
14
- verify: (accessToken: string, refreshToken: string, profile: Profile, done: VerifyCallback) => void
15
- },
16
- authenticateOptionsGoogle?: AuthenticateOptionsGoogle,
17
- }
18
-
19
- /** Provides a router and passport instance for Google OAuth */
20
- export default class PassportGoogle {
21
-
22
- private config: passportGoogleConfig;
23
- public router: Router = Router();
24
- public passport: PassportStatic = passport;
25
-
26
- constructor(config: passportGoogleConfig ) {
27
-
28
- this.config = config;
29
-
30
- this.passport.use(new GoogleStrategy(
31
- this.config.strategyConfig.options || {
32
- clientID: process.env.OAUTH_GOOGLE_CLIENTID || "",
33
- clientSecret: process.env.OAUTH_GOOGLE_CLIENTSECRET || "",
34
- callbackURL: `${process.env.APP_HOST}/auth/google/callback`,
35
- },
36
- this.config.strategyConfig.verify
37
- ));
38
-
39
- // redirect to google login
40
- this.router.get("/auth/google",
41
- this.passport.authenticate("google", this.config.authenticateOptionsGoogle || { scope: ["profile", "email"] })
42
- );
43
-
44
- // back from google login
45
- this.router.get("/auth/google/callback",
46
- this.passport.authenticate("google", { failureRedirect: "/login" }),
47
- (req, res) => {
48
- res.redirect("/profile");
49
- }
50
- );
51
- }
52
-
53
- public passportSerializeUser() {
54
- this.passport.serializeUser(async (user, done) => {
55
- log.info("passportGoogle().serializeUser", user);
56
- // Here, you can choose what data to store in the session.
57
- // This data will be used in `deserializeUser` to retrieve the full user object.
58
- // This is typically just the user's ID.
59
-
60
- // store role in session for access control
61
- const DbUser = await UserModel.findById(user);
62
- if (DbUser) {
63
- done(null, DbUser);
64
- } else {
65
- done(new Error("User not found"));
66
- }
67
-
68
- done(null, user);
69
- });
70
- }
71
-
72
- public async passportDeserializeUser() {
73
- this.passport.deserializeUser(async (id, done) => {
74
- log.info("passportGoogle().deserializeUser", id);
75
-
76
- const user = await UserModel.findById(id);
77
- if (user) {
78
- done(null, user);
79
- }
80
- else {
81
- done(new Error("User not found"));
82
- }
83
-
84
- });
85
- }
86
-
87
- }
@@ -1,39 +0,0 @@
1
- // {{headerComment}}
2
-
3
- import { Profile } from "passport";
4
- import { UserModel } from "./../_models/UserModel.gen";
5
-
6
- interface IProfile extends Profile {
7
- [key: string]: any;
8
- }
9
-
10
- export default async function oauthVerify(accessToken: string, refreshToken: string, profile: IProfile, done: (error: any, user?: any) => void) : Promise<void> {
11
- try {
12
-
13
- // find or create user
14
- const existingUser = await UserModel.findOne({ email: profile.emails?.[0].value });
15
-
16
- if( existingUser ){
17
- // log.info('OAuthVerify ExistingUser');
18
- return done(null, existingUser);
19
- }
20
- else {
21
- // log.info('OAuthVerify NewUser');
22
- const newUser = new UserModel({
23
- authProvider: profile.provider,
24
- email: profile.emails?.[0].value || "",
25
- authId: profile.id,
26
- name: profile.displayName,
27
- familyName: profile.name?.familyName,
28
- givenName: profile.name?.givenName,
29
- isActive: true,
30
- locale: profile._json?.locale,
31
- });
32
- newUser.save();
33
- return done(null, newUser);
34
- }
35
- }
36
- catch(err) {
37
- return done(err);
38
- }
39
- }
@@ -1,22 +0,0 @@
1
- export type accessAction = "create" | "read" | "update" | "delete" | "search";
2
- export const accessActionArr: accessAction[] = ["create", "read", "update", "delete", "search"];
3
-
4
- export interface accessControl< T = accessAction > {
5
- [key:string]: T[]
6
- }
7
-
8
- export class _RoleFactory<T = accessAction> {
9
- private accessControl: accessControl<T> = {};
10
-
11
- constructor(accessControl: accessControl<T>) {
12
- this.accessControl = accessControl;
13
- }
14
-
15
- public checkAccess(document: string, access: string): boolean {
16
- if (this.accessControl[document]) {
17
- return this.accessControl[document].includes(access as T);
18
- }
19
- return false;
20
- }
21
-
22
- }
@@ -1,70 +0,0 @@
1
- // {{headerComment}}
2
-
3
- import mongoose from "mongoose";
4
- import { Request, Response, NextFunction } from "express";
5
- import vex from "./../_utils/index.gen";
6
-
7
- export default class VexDbConnector {
8
- private mongoUrl: string;
9
- private sqlUrl: string;
10
-
11
-
12
- constructor(options:{
13
- mongoUrl?: string;
14
- sqlUrl?: string;
15
- }){
16
- this.mongoUrl = options.mongoUrl || "";
17
- this.sqlUrl = options.sqlUrl || "";
18
- }
19
-
20
- connectMongo() : mongoose.Connection | void {
21
- if ( !this.mongoUrl ){
22
- vex.log.error(`VexDbConnector : MongoUrl is not invalid "${this.mongoUrl}"`);
23
- return;
24
- }
25
- /**
26
- * @param retryTime time in second
27
- */
28
- const connectWithRetry = (retryTime: number = 10) : Promise<void | typeof mongoose> => {
29
- // vex.log.infoMongo("Connection with retry");
30
- return mongoose.connect(this.mongoUrl, {
31
- autoCreate: true,
32
- connectTimeoutMS: 5000,
33
- })
34
- .catch((err) => {
35
- vex.log.errorMongo(`Failed to Connect DB, Retrying in ${retryTime} seconds.`, err);
36
- setTimeout(connectWithRetry, retryTime*1000);
37
- });
38
- };
39
- connectWithRetry(10);
40
-
41
- mongoose.connection.on("open", () => {
42
- vex.log.infoMongo("MongoDB Connection open : " + this.mongoUrl);
43
- });
44
-
45
- mongoose.connection.on("error", (err: any) => {
46
- vex.log.errorMongo("MongoDB Connection error:", err.message, err);
47
- });
48
-
49
- return mongoose.connection;
50
- }
51
-
52
- middleware(req: Request, res: Response, next: NextFunction) {
53
- if (mongoose.connection.readyState !== 1) {
54
- vex.response.send(res, 503, "Database Connection Down");
55
- }
56
- else {
57
- mongoose.connection.collection("accessLogs").insertOne({
58
- timestamp: new Date().getTime(),
59
- ipa: req.socket.remoteAddress || req.headers["x-forwarded-for"],
60
- method: req.method,
61
- url: req.url.split("?")[0],
62
- headers: req.headers,
63
- // body: req.body,
64
- query: req.query,
65
- });
66
-
67
- next();
68
- }
69
- }
70
- }
@@ -1,20 +0,0 @@
1
- export enum responseMsg {
2
- permissionDeny = "Permission Denied",
3
- ok = "OK",
4
- notFound = "Not Found",
5
- queryError = "Query Error",
6
- validateError = "Validation Error",
7
- unexpectedError = "Unexpected Error",
8
- createFail = "Create Fail",
9
- updateFail = "Update Fail",
10
- deleteFail = "Delete Fail",
11
- }
12
-
13
- export interface responseObject<T>{
14
- ret_code : number,
15
- ret_msg : string,
16
- ret_time?: number,
17
- result: T,
18
- }
19
-
20
- export default responseMsg;
@@ -1,53 +0,0 @@
1
- // {{headerComment}}
2
-
3
- import jsYaml from "js-yaml";
4
- import fs from "fs";
5
-
6
- export function loadYaml(yamlFilePath: string) {
7
- try {
8
- return jsYaml.load(fs.readFileSync(yamlFilePath, "utf8"));
9
- } catch (e: any) {
10
- console.log("\x1b[41m%s\x1b[0m", "[ERROR]", "Error Load OpenApi File :\n", e);
11
- process.exit(0);
12
- }
13
- }
14
-
15
- /**
16
- * build mongoose select object
17
- * @param fieldsString json stringified array of string
18
- * @error may throw an error if the fieldsString is not a valid JSON
19
- */
20
- export function parseFieldsSelect(selectString: any) : { [key: string]: number } | undefined {
21
- const ErrorArrStrMsg = "Invalid select string, only array of string accepted";
22
-
23
- if (typeof selectString === "undefined" || selectString === "") {
24
- return undefined;
25
- }
26
- else if (typeof selectString !== "string") {
27
- throw new Error(ErrorArrStrMsg);
28
- }
29
-
30
- const fieldArr: string[] = JSON.parse(selectString);
31
-
32
- if (!Array.isArray(fieldArr)) {
33
- throw new Error(ErrorArrStrMsg);
34
- }
35
-
36
- for (let i = 0; i < fieldArr.length; i++) {
37
- if (typeof fieldArr[i] !== "string") {
38
- throw new Error(ErrorArrStrMsg);
39
- }
40
- }
41
- // Convert the fieldArr to an object that can be used in the select method
42
- const selectFields = fieldArr.reduce((obj: any, field: string) => {
43
- obj[field] = 1;
44
- return obj;
45
- }, {} as Record<string, number>);
46
-
47
- return selectFields;
48
- }
49
-
50
- export default {
51
- loadYaml,
52
- parseFieldsSelect
53
- };
@@ -1,11 +0,0 @@
1
- import logger from "./logger.gen";
2
- import response from "./response.gen";
3
- import { responseMsg } from "./../_types/responseMsg.gen";
4
- import common from "./common.gen";
5
-
6
- export default {
7
- log : logger,
8
- response,
9
- responseMsg : responseMsg ,
10
- common
11
- };