very-express 0.4.2 → 0.4.3

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.
@@ -31,7 +31,7 @@ export default class PassportGoogle {
31
31
  this.config.strategyConfig.options || {
32
32
  clientID: process.env.OAUTH_GOOGLE_CLIENTID || "",
33
33
  clientSecret: process.env.OAUTH_GOOGLE_CLIENTSECRET || "",
34
- callbackURL: `${process.env.APP_HOST}:${process.env.APP_PORT}/auth/google/callback`,
34
+ callbackURL: `${process.env.APP_HOST}/auth/google/callback`,
35
35
  },
36
36
  this.config.strategyConfig.verify
37
37
  ));
@@ -0,0 +1,70 @@
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,4 +1,4 @@
1
- enum responseMessage {
1
+ export enum responseMsg {
2
2
  permissionDeny = "Permission Denied",
3
3
  ok = "OK",
4
4
  notFound = "Not Found",
@@ -10,4 +10,11 @@ enum responseMessage {
10
10
  deleteFail = "Delete Fail",
11
11
  }
12
12
 
13
- export default responseMessage;
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,11 +1,11 @@
1
1
  import logger from "./logger.gen";
2
2
  import response from "./response.gen";
3
- import responseMessage from "../../system/_types/responseMsg.gen";
3
+ import { responseMsg } from "./../_types/responseMsg.gen";
4
4
  import common from "./common.gen";
5
5
 
6
6
  export default {
7
7
  log : logger,
8
8
  response,
9
- responseMsg : responseMessage,
9
+ responseMsg : responseMsg ,
10
10
  common
11
11
  };
@@ -19,10 +19,32 @@ export function error(msg: any, ...optionalParams: any[]): never {
19
19
  process.exit(1);
20
20
  }
21
21
 
22
+ // wrapper
23
+ export function infoMongo(msg: any, ...optionalParams: any[]): void {
24
+ info("[MONGO]", msg, optionalParams);
25
+ }
26
+
27
+ export function errorMongo(msg: any, ...optionalParams: any[]): never {
28
+ error("[MONGO]", msg, optionalParams);
29
+ }
30
+
31
+ export function infoSql(msg: any, ...optionalParams: any[]): void {
32
+ info("[SQL]", msg, optionalParams);
33
+ }
34
+
35
+ export function errorSql(msg: any, ...optionalParams: any[]): never {
36
+ error("[SQL]", msg, optionalParams);
37
+ }
38
+
22
39
  export default {
23
40
  process : processing,
24
41
  ok,
25
42
  info,
26
43
  warn,
27
44
  error,
45
+
46
+ infoMongo,
47
+ errorMongo,
48
+ infoSql,
49
+ errorSql,
28
50
  };
@@ -1,17 +1,12 @@
1
1
  import { Response } from "express";
2
-
3
- export interface responseObject<T>{
4
- ret_code : number,
5
- ret_msg : string,
6
- ret_time?: number,
7
- result: T,
8
- }
2
+ // import { responseObject } from "./../_types/responseMsg.gen";
9
3
 
10
4
  /**
11
5
  * @param res express response object
12
6
  * @param code http status
13
7
  * @param message response data message
14
8
  * @param result response data result
9
+ * @returns express response object
15
10
  */
16
11
  export function send<T = undefined>(
17
12
  res: Response,
package/dist/index.js CHANGED
@@ -661,7 +661,7 @@ import express from 'express';
661
661
  import dotenv from 'dotenv';
662
662
  import helmet from 'helmet';
663
663
  import log from './system/_utils/logger.gen';
664
- import mongoConn from './system/_services/mongoConn.gen';
664
+ import VexDbConnector from './system/_services/VexDbConnector.gen';
665
665
 
666
666
  import ApiRouter from './system/_routes/ApiRouter.gen';
667
667
  {{Import}}
@@ -677,6 +677,11 @@ const helmetConfig = {
677
677
  xDnsPrefetchControl: { allow: false },
678
678
  };
679
679
 
680
+ const vexDB = new VexDbConnector({
681
+ mongoUrl: process.env.MONGODB_URI,
682
+ });
683
+
684
+
680
685
  const ApiRoute = new ApiRouter(); ApiRoute.initRoutes();
681
686
  {{Config}}
682
687
 
@@ -692,7 +697,6 @@ async function main(): Promise<void> {
692
697
  // UseMiddleware
693
698
  app.use(express.json());
694
699
  app.use(helmet(helmetConfig));
695
- app.use(mongoConn.middleware);
696
700
 
697
701
  // UsePlugins
698
702
  {{AppUse}}
@@ -717,8 +721,8 @@ async function main(): Promise<void> {
717
721
 
718
722
  app.listen(3000, () => {
719
723
  if(!process.env.MONGODB_URI) throw new Error('MONGODB_URI is not defined');
720
- mongoConn.connect(process.env.MONGODB_URI);
721
- log.ok(\`Server is running on : \${process.env.APP_HOST}:\${process.env.APP_PORT}\`);
724
+ vexDB.connectMongo();
725
+ log.ok(\`Server is running on : \${process.env.APP_HOST}\`);
722
726
  });
723
727
 
724
728
  }
@@ -952,7 +956,7 @@ import util from 'util';
952
956
  export default class OAuthRouter{
953
957
 
954
958
  public router: Router = Router();
955
- private loginHtml = ${function(e){let t="<p> login with : </p>";return e.forEach(e=>{t+=`<a href="\${process.env.APP_HOST}:\${process.env.APP_PORT}/auth/${e}">${e}</a>`}),`\`${t}\``}(t)};
959
+ private loginHtml = ${function(e){let t="<p> login with : </p>";return e.forEach(e=>{t+=`<a href="\${process.env.APP_HOST}/auth/${e}">${e}</a>`}),`\`${t}\``}(t)};
956
960
 
957
961
  constructor() {}
958
962
 
@@ -31,7 +31,7 @@ export default class PassportGoogle {
31
31
  this.config.strategyConfig.options || {
32
32
  clientID: process.env.OAUTH_GOOGLE_CLIENTID || "",
33
33
  clientSecret: process.env.OAUTH_GOOGLE_CLIENTSECRET || "",
34
- callbackURL: `${process.env.APP_HOST}:${process.env.APP_PORT}/auth/google/callback`,
34
+ callbackURL: `${process.env.APP_HOST}/auth/google/callback`,
35
35
  },
36
36
  this.config.strategyConfig.verify
37
37
  ));
@@ -0,0 +1,70 @@
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,4 +1,4 @@
1
- enum responseMessage {
1
+ export enum responseMsg {
2
2
  permissionDeny = "Permission Denied",
3
3
  ok = "OK",
4
4
  notFound = "Not Found",
@@ -10,4 +10,11 @@ enum responseMessage {
10
10
  deleteFail = "Delete Fail",
11
11
  }
12
12
 
13
- export default responseMessage;
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,11 +1,11 @@
1
1
  import logger from "./logger.gen";
2
2
  import response from "./response.gen";
3
- import responseMessage from "../../system/_types/responseMsg.gen";
3
+ import { responseMsg } from "./../_types/responseMsg.gen";
4
4
  import common from "./common.gen";
5
5
 
6
6
  export default {
7
7
  log : logger,
8
8
  response,
9
- responseMsg : responseMessage,
9
+ responseMsg : responseMsg ,
10
10
  common
11
11
  };
@@ -19,10 +19,32 @@ export function error(msg: any, ...optionalParams: any[]): never {
19
19
  process.exit(1);
20
20
  }
21
21
 
22
+ // wrapper
23
+ export function infoMongo(msg: any, ...optionalParams: any[]): void {
24
+ info("[MONGO]", msg, optionalParams);
25
+ }
26
+
27
+ export function errorMongo(msg: any, ...optionalParams: any[]): never {
28
+ error("[MONGO]", msg, optionalParams);
29
+ }
30
+
31
+ export function infoSql(msg: any, ...optionalParams: any[]): void {
32
+ info("[SQL]", msg, optionalParams);
33
+ }
34
+
35
+ export function errorSql(msg: any, ...optionalParams: any[]): never {
36
+ error("[SQL]", msg, optionalParams);
37
+ }
38
+
22
39
  export default {
23
40
  process : processing,
24
41
  ok,
25
42
  info,
26
43
  warn,
27
44
  error,
45
+
46
+ infoMongo,
47
+ errorMongo,
48
+ infoSql,
49
+ errorSql,
28
50
  };
@@ -1,17 +1,12 @@
1
1
  import { Response } from "express";
2
-
3
- export interface responseObject<T>{
4
- ret_code : number,
5
- ret_msg : string,
6
- ret_time?: number,
7
- result: T,
8
- }
2
+ // import { responseObject } from "./../_types/responseMsg.gen";
9
3
 
10
4
  /**
11
5
  * @param res express response object
12
6
  * @param code http status
13
7
  * @param message response data message
14
8
  * @param result response data result
9
+ * @returns express response object
15
10
  */
16
11
  export function send<T = undefined>(
17
12
  res: Response,
@@ -1,5 +1,4 @@
1
- APP_HOST=http://localhost
2
- APP_PORT=3000
1
+ APP_HOST=http://localhost:3000
3
2
  MONGODB_URI=mongodb://localhost:27017/veryExpressDB
4
3
 
5
4
  OAUTH_GOOGLE_CLIENTID=
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "very-express",
3
- "version": "0.4.2",
3
+ "version": "0.4.3",
4
4
  "description": "based on json schema and openapi, generate Express RestApi server with mongoDb ",
5
5
  "author": "justin26l",
6
6
  "license": "MIT",