very-express 0.5.25 → 0.6.0-alpha

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 (60) hide show
  1. package/.eslintrc.json +36 -37
  2. package/.gitattributes +2 -2
  3. package/.github/copilot-instructions.md +107 -0
  4. package/.github/workflows/npm-start.yml +23 -23
  5. package/LICENSE +21 -21
  6. package/README.md +75 -62
  7. package/dist/index.js +1070 -1285
  8. package/dist/templates/_controllers/_ControllerFactory.ts +7 -3
  9. package/dist/templates/_middlewares/Authentication.ts +1 -5
  10. package/dist/templates/_middlewares/tsoaAuthentication.ts +24 -0
  11. package/dist/templates/_projectSettings/env +25 -22
  12. package/dist/templates/_projectSettings/package.json +50 -50
  13. package/dist/templates/_services/MongooseRepositoryAdapter.ts +48 -0
  14. package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +59 -0
  15. package/dist/templates/_services/VexDb.ts +14 -0
  16. package/dist/templates/_services/VexDbConnector.ts +143 -58
  17. package/dist/templates/_services/VexSystem.ts +25 -26
  18. package/dist/templates/_services/auth/JWTService.ts +26 -13
  19. package/dist/templates/_services/oauth/OAuthProfileMap.ts +6 -14
  20. package/dist/templates/_services/oauth/OAuthStrategyService.ts +70 -51
  21. package/dist/templates/_types/IVexRepository.ts +18 -0
  22. package/dist/templates/_types/VexRequest.ts +11 -0
  23. package/dist/templates/_types/VexResponse.ts +25 -0
  24. package/dist/templates/_types/VexResponseError.ts +4 -3
  25. package/dist/templates/_types/responseObject.ts +1 -1
  26. package/dist/templates/_utils/common.ts +50 -16
  27. package/dist/templates/_utils/hash.ts +6 -5
  28. package/dist/templates/_utils/index.ts +2 -1
  29. package/dist/templates/_utils/logger.ts +16 -15
  30. package/dist/templates/_utils/processTimer.ts +1 -0
  31. package/dist/templates/_utils/response.ts +4 -3
  32. package/dist/templates/_utils/validator.ts +1 -0
  33. package/dist/templates/jsonSchema/Session.json +34 -31
  34. package/dist/templates/jsonSchema/User.json +50 -85
  35. package/dist/templates/jsonSchema/UserAuthProfiles.json +48 -0
  36. package/dist/templates/root/Dockerfile +19 -19
  37. package/dist/templates/root/README.md +38 -38
  38. package/dist/templates/root/public/css/style.css +7 -7
  39. package/dist/templates/root/public/js/login.js +58 -58
  40. package/dist/templates/root/public/js/logincallback.js +18 -18
  41. package/dist/templates/root/public/js/mytokens.js +10 -10
  42. package/dist/templates/root/public/js/refreshtokens.js +22 -22
  43. package/dist/templates/root/scripts/build.js +38 -38
  44. package/dist/templates/root/tsconfig.json +29 -21
  45. package/docs/ForeignKey.md +43 -43
  46. package/docs/appGenerated/auth.md +22 -22
  47. package/docs/developmentNote.md +22 -22
  48. package/docs/releaseNote/v0-5-0.md +17 -17
  49. package/docs/roadMap/futurePlan.md +9 -0
  50. package/docs/roadMap/released.md +49 -49
  51. package/docs/roadMap/v0-6-0.md +15 -15
  52. package/docs/vexJsonSchema.md +55 -55
  53. package/package.json +59 -51
  54. package/scripts/build.js +13 -13
  55. package/scripts/bump-version.js +87 -0
  56. package/scripts/copyTsTemplates.js +30 -30
  57. package/scripts/merge.js +124 -124
  58. package/tsconfig.json +121 -121
  59. package/vex.config.json +37 -36
  60. package/docs/roadMap/v0-7-0.md +0 -5
@@ -1,10 +1,14 @@
1
1
  // {{headerComment}}
2
- export class _ControllerFactory {
2
+ import { Controller } from "tsoa";
3
3
 
4
- constructor() {}
4
+ export class _ControllerFactory extends Controller {
5
+
6
+ constructor() {
7
+ super();
8
+ }
5
9
 
6
10
  protected isObjectId(id: string): boolean {
7
11
  return /^[0-9a-fA-F]{24}$/.test(id);
8
12
  }
9
-
13
+
10
14
  }
@@ -12,7 +12,7 @@ export default class Authentication {
12
12
  public middleware = (req: Request, res: Response, next: NextFunction) => {
13
13
  try {
14
14
  // gate keeper
15
- log.info("Authentication.middleware", req.headers["x-auth-index"], req.headers.authorization);
15
+ // log.info("Authentication.middleware", req.headers["x-auth-index"], req.headers.authorization);
16
16
  const token = req.headers.authorization?.split(" ")[1];
17
17
  const accessTokenIndex = req.headers["x-auth-index"]?.toString();
18
18
 
@@ -26,9 +26,6 @@ export default class Authentication {
26
26
 
27
27
  // verify token
28
28
  const tokenData = this.JWTService.verifyToken(token, accessTokenIndex);
29
-
30
- // set req.user to the decoded token
31
- log.info("tokenValid", tokenData);
32
29
  req.user = tokenData;
33
30
  next();
34
31
  }
@@ -40,7 +37,6 @@ export default class Authentication {
40
37
  response.send(res, 400, { message: e?.message});
41
38
  }
42
39
  else {
43
- log.errorNoExit(e);
44
40
  response.send(res, 500, { message: e?.message});
45
41
  }
46
42
  }
@@ -0,0 +1,24 @@
1
+ // {{headerComment}}
2
+ import { Request } from "express";
3
+ import VexResponseError from "../_types/VexResponseError.gen";
4
+
5
+ /**
6
+ * Called by tsoa-generated routes for every @Security decorator.
7
+ * securityName matches the key in tsoa.json securityDefinitions.
8
+ */
9
+ export async function expressAuthentication(
10
+ request: Request,
11
+ securityName: string,
12
+ _scopes?: string[]
13
+ ): Promise<unknown> {
14
+
15
+ if (securityName === "BearerAuth" && !request.headers["authorization"]) {
16
+ throw new VexResponseError(401, null, "Missing Authorization header");
17
+ }
18
+
19
+ if (securityName === "AuthIndex" && !request.headers["x-auth-index"]) {
20
+ throw new VexResponseError(401, null, "Missing X-Auth-Index header");
21
+ }
22
+
23
+ return {};
24
+ }
@@ -1,23 +1,26 @@
1
- APP_HOST=http://localhost
2
- APP_PORT=3000
3
- MONGODB_URI=mongodb://localhost:27017/veryExpressDB
4
-
5
- LOGIN_SUCCESS_REDIRECT_PATH=/logincallback
6
- LOGIN_FAILED_REDIRECT_PATH=/logincallback
7
-
8
- # OAUTH
9
- OAUTH_GOOGLE_CLIENTID=
10
- OAUTH_GOOGLE_CLIENTSECRET=
11
- OAUTH_GITHUB_CLIENTID=
12
- OAUTH_GITHUB_CLIENTSECRET=
13
- # OAUTH_MICROSOFT_CLIENTID=
14
- # OAUTH_MICROSOFT_CLIENTSECRET=
15
- # OAUTH_APPLE_CLIENTID=
16
- # OAUTH_APPLE_CLIENTSECRET=
17
-
18
- # JWT token
19
- ACCESS_TOKEN_EXPIRE_TIME='5m'
20
- REFRESH_TOKEN_EXPIRE_TIME='15m'
21
- SESSION_COOKIE_SECRET='my-session-cookie-secret'
22
- JWT_ALGORITHM='HS256'
1
+ APP_HOST=http://localhost
2
+ APP_PORT=3000
3
+ MONGODB_URI=mongodb://localhost:27017/veryExpressDB
4
+ SQL_URI=postgresql://username:password@localhost:5432/mydatabase
5
+ SQL_CA=""
6
+ SQL_SYNCHRONIZE=true
7
+
8
+ LOGIN_SUCCESS_REDIRECT_PATH=/logincallback
9
+ LOGIN_FAILED_REDIRECT_PATH=/logincallback
10
+
11
+ # OAUTH
12
+ OAUTH_GOOGLE_CLIENTID=
13
+ OAUTH_GOOGLE_CLIENTSECRET=
14
+ OAUTH_GITHUB_CLIENTID=
15
+ OAUTH_GITHUB_CLIENTSECRET=
16
+ # OAUTH_MICROSOFT_CLIENTID=
17
+ # OAUTH_MICROSOFT_CLIENTSECRET=
18
+ # OAUTH_APPLE_CLIENTID=
19
+ # OAUTH_APPLE_CLIENTSECRET=
20
+
21
+ # JWT token
22
+ ACCESS_TOKEN_EXPIRE_TIME='5m'
23
+ REFRESH_TOKEN_EXPIRE_TIME='15m'
24
+ SESSION_COOKIE_SECRET='my-session-cookie-secret'
25
+ JWT_ALGORITHM='HS256'
23
26
  JWT_SECRET0='my-secret-key0'
@@ -1,50 +1,50 @@
1
- {
2
- "main": "index.js",
3
- "scripts": {
4
- "build": "tsc -p . && node scripts/build.js",
5
- "start": "node dist/server.js",
6
- "dev": "nodemon --watch src --exec ts-node src/server.ts",
7
- "docker-build": "docker build -t very-express .",
8
- "docker-start": "docker run -p 3000:3000 very-express"
9
- },
10
- "dependencies": {
11
- "cookie": "^0.6.0",
12
- "cookie-parser": "^1.4.6",
13
- "dotenv": "^16.4.4",
14
- "express": "^4.18.2",
15
- "express-validator": "^7.0.1",
16
- "helmet": "^7.1.0",
17
- "js-yaml": "^4.1.0",
18
- "jsonwebtoken": "^9.0.2",
19
- "mongo-ts-querystring": "^1.0.4",
20
- "mongodb": "^5.6.0",
21
- "mongoose": "^7.4.0",
22
- "passport": "^0.7.0",
23
- "passport-google-oauth20": "^2.0.0",
24
- "passport-github": "^1.1.0",
25
- "passport-jwt": "^4.0.1",
26
- "swagger-ui-express": "^5.0.0"
27
- },
28
- "devDependencies": {
29
- "@types/cookie-parser": "^1.4.7",
30
- "@types/jsonwebtoken": "^9.0.7",
31
- "@types/crypto-js": "^4.1.2",
32
- "@types/dotenv": "^8.2.0",
33
- "@types/express": "^4.17.17",
34
- "@types/express-validator": "^3.0.0",
35
- "@types/js-yaml": "^4.0.9",
36
- "@types/mongodb": "^4.0.7",
37
- "@types/ms": "^2.1.0",
38
- "@types/node": "^20.4.2",
39
- "@types/passport": "^1.0.16",
40
- "@types/passport-google-oauth20": "^2.0.14",
41
- "@types/passport-github": "^1.1.12",
42
- "@types/sequelize": "^4.28.15",
43
- "@types/swagger-ui-express": "^4.1.6",
44
- "@types/ws": "^8.5.5",
45
- "nodemon": "^2.0.22",
46
- "strip-json-comments": "^5.0.1",
47
- "ts-node": "^10.9.1",
48
- "typescript": "^5.1.6"
49
- }
50
- }
1
+ {
2
+ "main": "index.js",
3
+ "scripts": {
4
+ "build": "npm run openapi && tsc -p . && node scripts/build.js",
5
+ "start": "node dist/server.js",
6
+ "dev": "nodemon --watch src --ext ts --ignore src/system/_routes/tsoa_routes.ts --ignore src/openapi/ --exec \"tsoa spec-and-routes && ts-node src/server.ts\"",
7
+ "openapi": "tsoa spec-and-routes",
8
+ "docker-build": "docker build -t very-express .",
9
+ "docker-start": "docker run -p 3000:3000 very-express"
10
+ },
11
+ "dependencies": {
12
+ "cookie": "^0.6.0",
13
+ "cookie-parser": "^1.4.6",
14
+ "dotenv": "^16.4.4",
15
+ "express": "^4.18.2",
16
+ "helmet": "^7.1.0",
17
+ "js-yaml": "^4.1.0",
18
+ "jsonwebtoken": "^9.0.2",
19
+ "passport": "^0.7.0",
20
+ "passport-github": "^1.1.0",
21
+ "passport-google-oauth20": "^2.0.0",
22
+ "passport-jwt": "^4.0.1",
23
+ "pg": "^8.20.0",
24
+ "reflect-metadata": "^0.2.2",
25
+ "swagger-ui-express": "^5.0.0",
26
+ "tsoa": "^7.0.0-alpha.0",
27
+ "typeorm": "^0.3.20"
28
+ },
29
+ "devDependencies": {
30
+ "@types/cookie-parser": "^1.4.7",
31
+ "@types/crypto-js": "^4.1.2",
32
+ "@types/dotenv": "^8.2.0",
33
+ "@types/express": "^4.17.17",
34
+ "@types/js-yaml": "^4.0.9",
35
+ "@types/jsonwebtoken": "^9.0.7",
36
+ "@types/mongodb": "^4.0.7",
37
+ "@types/ms": "^2.1.0",
38
+ "@types/node": "^20.4.2",
39
+ "@types/passport": "^1.0.16",
40
+ "@types/passport-github": "^1.1.12",
41
+ "@types/passport-google-oauth20": "^2.0.14",
42
+ "@types/pg": "^8.11.0",
43
+ "@types/swagger-ui-express": "^4.1.6",
44
+ "@types/ws": "^8.5.5",
45
+ "nodemon": "^2.0.22",
46
+ "strip-json-comments": "^5.0.1",
47
+ "ts-node": "^10.9.1",
48
+ "typescript": "^5.1.6"
49
+ }
50
+ }
@@ -0,0 +1,48 @@
1
+ // {{headerComment}}
2
+ import { Model, Document, FilterQuery } from "mongoose";
3
+ import { IVexRepository } from "../_types/IVexRepository.gen";
4
+ import { Select, Filter, Join } from "../_types/VexRequest.gen";
5
+
6
+ export class MongooseRepositoryAdapter<T extends Document> implements IVexRepository<T> {
7
+ constructor(private model: Model<T>) {}
8
+
9
+ public get native(): Model<T> {
10
+ return this.model;
11
+ }
12
+
13
+ find(filter: Filter, join?: Join, select?: Select): Promise<T[]> {
14
+ // TODO: handle join and select
15
+ return this.model.find((filter || {}) as FilterQuery<T>).exec();
16
+ }
17
+
18
+ findOne(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
19
+ // TODO: handle join and select
20
+ return this.model.findOne(filter as FilterQuery<T>).exec();
21
+ }
22
+
23
+ findOneWhere(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
24
+ // TODO: handle join and select
25
+ return this.model.findOne(filter as FilterQuery<T>).exec();
26
+ }
27
+
28
+ async create(data: Partial<T>): Promise<T> {
29
+ const doc = new this.model(data);
30
+ return doc.save();
31
+ }
32
+
33
+ replace(id: string | number, data: Partial<T>): Promise<T | null> {
34
+ return this.model.findByIdAndUpdate(id, data, { new: true, overwrite: true }).exec();
35
+ }
36
+
37
+ update(id: string | number, data: Partial<T>): Promise<T | null> {
38
+ return this.model.findByIdAndUpdate(id, { $set: data }, { new: true }).exec();
39
+ }
40
+
41
+ async delete(id: string | number): Promise<void> {
42
+ await this.model.findByIdAndDelete(id).exec();
43
+ }
44
+
45
+ async deleteWhere(filter: Record<string, unknown>): Promise<void> {
46
+ await this.model.deleteOne(filter as FilterQuery<T>).exec();
47
+ }
48
+ }
@@ -0,0 +1,59 @@
1
+ // {{headerComment}}
2
+ import { Repository, ObjectLiteral, FindOptionsWhere, DeepPartial } from "typeorm";
3
+ import { IVexRepository } from "../_types/IVexRepository.gen";
4
+ import { Select, Filter, Join } from "../_types/VexRequest.gen";
5
+
6
+ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements IVexRepository<T> {
7
+ constructor(private repo: Repository<T>) {}
8
+
9
+ public get native(): Repository<T> {
10
+ return this.repo;
11
+ }
12
+
13
+ find(filter: Filter, join?: Join, select?: Select): Promise<T[]> {
14
+ return this.repo.find({
15
+ select,
16
+ where: filter as FindOptionsWhere<T>,
17
+ relations: join
18
+ });
19
+ }
20
+
21
+ findOne(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
22
+ return this.repo.findOne({
23
+ select,
24
+ where: filter as FindOptionsWhere<T>,
25
+ relations: join
26
+ });
27
+ }
28
+
29
+ findOneWhere(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
30
+ return this.repo.findOne({
31
+ select,
32
+ where: filter as FindOptionsWhere<T>,
33
+ relations: join
34
+ });
35
+ }
36
+
37
+ async create(data: Partial<T>): Promise<T> {
38
+ return this.repo.save(this.repo.create(data as DeepPartial<T>));
39
+ }
40
+
41
+ async replace(id: string | number, data: Partial<T>): Promise<T | null> {
42
+ const existing = await this.findOne({ _id: id });
43
+ if (!existing) return null;
44
+ return this.repo.save(this.repo.merge(existing, data as DeepPartial<T>));
45
+ }
46
+
47
+ async update(id: string | number, data: Partial<T>): Promise<T | null> {
48
+ await this.repo.update({ _id: id } as unknown as FindOptionsWhere<T>, data as any);
49
+ return this.findOne({ _id: id });
50
+ }
51
+
52
+ async delete(id: string | number): Promise<void> {
53
+ await this.repo.delete({ _id: id } as unknown as FindOptionsWhere<T>);
54
+ }
55
+
56
+ async deleteWhere(filter: Record<string, unknown>): Promise<void> {
57
+ await this.repo.delete(filter as FindOptionsWhere<T>);
58
+ }
59
+ }
@@ -0,0 +1,14 @@
1
+ // {{headerComment}}
2
+ import { VexDbConnector } from "./VexDbConnector.gen";
3
+ import dotenv from "dotenv";
4
+
5
+ dotenv.config();
6
+
7
+ const VexDb = new VexDbConnector({
8
+ sqlUrl: process.env.SQL_URI ?? undefined,
9
+ sqlCa: process.env.SQL_CA ?? undefined,
10
+ mongoUrl: process.env.MONGO_URI ?? undefined,
11
+ recordAccessLog: false,
12
+ });
13
+
14
+ export default VexDb;
@@ -1,86 +1,171 @@
1
1
  // {{headerComment}}
2
- import mongoose from "mongoose";
3
2
  import { Request, Response, NextFunction } from "express";
3
+ import { DataSource, EntityTarget, ObjectLiteral } from "typeorm";
4
+ import mongoose, { Document } from "mongoose";
5
+ import { sqlMigrations } from "../_models/sqlMigration.gen";
6
+ import { IVexRepository } from "../_types/IVexRepository.gen";
7
+ import { TypeOrmRepositoryAdapter } from "./TypeOrmRepositoryAdapter.gen";
8
+ import { MongooseRepositoryAdapter } from "./MongooseRepositoryAdapter.gen";
4
9
  import utils from "./../_utils";
5
10
 
6
- export default class VexDbConnector {
7
- private mongoUrl: string;
11
+ export class VexDbConnector {
8
12
  private sqlUrl: string;
9
-
13
+ private sqlCa: string;
14
+ private mongoUrl: string;
10
15
  private recordAccessLog: boolean = false;
11
16
 
12
- constructor(options:{
13
- mongoUrl?: string;
17
+ public dataSource?: DataSource;
18
+
19
+ constructor(options: {
14
20
  sqlUrl?: string;
21
+ sqlCa?: string;
22
+ mongoUrl?: string;
15
23
  recordAccessLog?: boolean;
16
- }){
17
- this.mongoUrl = options.mongoUrl || "";
24
+ }) {
18
25
  this.sqlUrl = options.sqlUrl || "";
26
+ this.sqlCa = options.sqlCa || "";
27
+ this.mongoUrl = options.mongoUrl || "";
19
28
  this.recordAccessLog = options.recordAccessLog || false;
20
-
21
- // Bind the middleware method to the instance
22
29
  this.middleware = this.middleware.bind(this);
23
30
  }
24
-
25
-
26
- connectMongo() : mongoose.Connection | void {
27
- if ( !this.mongoUrl ){
28
- utils.log.error("VexDbConnector : MongoUrl is not invalid");
29
- return;
31
+
32
+ connect(): void {
33
+ if (this.sqlUrl) this.connectSql();
34
+ if (this.mongoUrl) this.connectMongo();
35
+ }
36
+
37
+ close(): void {
38
+ if (this.sqlUrl) this.closeSql();
39
+ if (this.mongoUrl) this.closeMongo();
40
+ }
41
+
42
+ connectSql(): void {
43
+ utils.log.infoSql("Connecting to SQL DB (TypeORM)...");
44
+
45
+ const caRaw = this.sqlCa || undefined;
46
+ let ca: string | undefined;
47
+ if (caRaw) {
48
+ ca = caRaw.startsWith("-----BEGIN") ? caRaw : Buffer.from(caRaw, "base64").toString("utf8");
30
49
  }
31
- /**
32
- * @param retryTime time in second
33
- */
34
- const connectWithRetry = (retryTime: number = 10) : Promise<void | typeof mongoose> => {
35
- // utils.log.infoMongo("Connection with retry");
36
- return mongoose.connect(this.mongoUrl, {
37
- autoCreate: true,
38
- connectTimeoutMS: 5000,
39
- })
50
+ const insecure = (process.env.SQL_INSECURE_TLS || "").toLowerCase() === "true";
51
+ const ssl = insecure
52
+ ? { rejectUnauthorized: false }
53
+ : (ca ? { rejectUnauthorized: true, ca } : undefined);
54
+
55
+ const sqlUrl = new URL(this.sqlUrl);
56
+ const ds = new DataSource({
57
+ type: "postgres",
58
+ host: sqlUrl.hostname,
59
+ port: Number(sqlUrl.port) || 5432,
60
+ username: sqlUrl.username,
61
+ password: sqlUrl.password,
62
+ database: sqlUrl.pathname.slice(1),
63
+ ssl,
64
+ synchronize: (process.env.SQL_SYNCHRONIZE || "").toLowerCase() === "true",
65
+ logging: false,
66
+ entities: [__dirname + "/../_models/*.gen.{ts,js}"],
67
+ migrations: [],
68
+ });
69
+
70
+ const connectWithRetry = (retryTime = 10): void => {
71
+ ds.initialize()
72
+ .then(() => {
73
+ this.dataSource = ds;
74
+ utils.log.infoSql("TypeORM DataSource initialized");
75
+ this.runSqlMigrations(ds);
76
+ })
40
77
  .catch((err) => {
41
- utils.log.errorMongo(`Failed to Connect DB, Retrying in ${retryTime} seconds.`, err);
42
- setTimeout(connectWithRetry, retryTime*1000);
78
+ utils.log.errorSql(`Failed to initialize TypeORM, retrying in ${retryTime}s`, err);
79
+ setTimeout(() => connectWithRetry(retryTime), retryTime * 1000);
43
80
  });
44
81
  };
82
+
45
83
  connectWithRetry(10);
84
+ }
46
85
 
47
- mongoose.connection.on("open", () => {
48
- utils.log.infoMongo("MongoDB Connection open");
49
- });
86
+ private async runSqlMigrations(ds: DataSource): Promise<void> {
87
+ if (!sqlMigrations.length) return;
88
+ const runner = ds.createQueryRunner();
89
+ await runner.connect();
90
+ try {
91
+ for (const sql of sqlMigrations) {
92
+ utils.log.infoSql(`Applying migration: ${sql}`);
93
+ await runner.query(sql);
94
+ }
95
+ utils.log.infoSql(`${sqlMigrations.length} migrations applied`);
96
+ } catch (err) {
97
+ utils.log.errorSql("SQL migration failed", err);
98
+ } finally {
99
+ await runner.release();
100
+ }
101
+ }
50
102
 
51
- mongoose.connection.on("error", (err: any) => {
52
- utils.log.errorMongo("MongoDB Connection error: ", err.message, err);
53
- });
103
+ closeSql(): void {
104
+ if (this.dataSource?.isInitialized) {
105
+ this.dataSource.destroy()
106
+ .then(() => utils.log.infoSql("TypeORM DataSource closed"))
107
+ .catch((err) => utils.log.errorSql("Error closing TypeORM DataSource", err));
108
+ }
109
+ }
54
110
 
55
- return mongoose.connection;
111
+ connectMongo(): void {
112
+ utils.log.infoSql("Connecting to MongoDB (Mongoose)...");
113
+ const connectWithRetry = (retryTime = 10): void => {
114
+ mongoose.connect(this.mongoUrl)
115
+ .then(() => utils.log.infoSql("Mongoose connected"))
116
+ .catch((err) => {
117
+ utils.log.errorSql(`Failed to connect Mongoose, retrying in ${retryTime}s`, err);
118
+ setTimeout(() => connectWithRetry(retryTime), retryTime * 1000);
119
+ });
120
+ };
121
+ connectWithRetry(10);
122
+ }
123
+
124
+ closeMongo(): void {
125
+ mongoose.disconnect()
126
+ .then(() => utils.log.infoSql("Mongoose disconnected"))
127
+ .catch((err) => utils.log.errorSql("Error disconnecting Mongoose", err));
56
128
  }
57
129
 
58
- /**
59
- * Database Middleware
60
- * Feature:
61
- * - restrict access to app when DB connection down.
62
- * - record access log
63
- **/
64
- middleware(req: Request, res: Response, next: NextFunction) {
65
- if (mongoose.connection.readyState !== 1) {
66
- utils.response.send(res, 503, {
67
- code: utils.response.code.DB_CONN_ERR,
68
- });
130
+ getRepository<T extends Document>(target: { schema: unknown; modelName: string }): IVexRepository<T>;
131
+ getRepository<T extends ObjectLiteral>(target: EntityTarget<T>): IVexRepository<T>;
132
+ getRepository<T>(target: EntityTarget<ObjectLiteral> | any): IVexRepository<T> {
133
+ // Mongoose Model: has .schema and .modelName properties
134
+ if (target?.schema && target?.modelName) {
135
+ return new MongooseRepositoryAdapter<T & Document>(target);
69
136
  }
70
- else if (this.recordAccessLog){
71
- mongoose.connection.collection("accessLogs").insertOne({
72
- timestamp: new Date().getTime(),
73
- ipa: req.socket.remoteAddress || req.headers["x-forwarded-for"],
74
- method: req.method,
75
- url: req.url.split("?")[0],
76
- headers: req.headers,
77
- // body: req.body,
78
- query: req.query,
79
- });
137
+ if (!this.dataSource) throw new Error("SQL DataSource not initialized");
138
+ return new TypeOrmRepositoryAdapter<T & ObjectLiteral>(this.dataSource.getRepository(target));
139
+ }
140
+
141
+ async middleware(req: Request, res: Response, next: NextFunction): Promise<void> {
142
+ try {
143
+ if (this.sqlUrl && (!this.dataSource || !this.dataSource.isInitialized)) {
144
+ utils.response.send(res, 503, { code: utils.response.code.DB_CONN_ERR });
145
+ return;
146
+ }
147
+
148
+ if (this.recordAccessLog && this.dataSource?.isInitialized) {
149
+ const logEntry = {
150
+ timestamp: new Date().getTime(),
151
+ ipa: req.socket.remoteAddress || req.headers["x-forwarded-for"],
152
+ method: req.method,
153
+ url: req.url.split("?")[0],
154
+ headers: JSON.stringify(req.headers),
155
+ query: JSON.stringify(req.query),
156
+ };
157
+ try {
158
+ await this.dataSource.getRepository("AccessLog").save(logEntry);
159
+ }
160
+ catch { /* table may not exist */ }
161
+ }
162
+
80
163
  next();
81
164
  }
82
- else{
83
- next();
165
+ catch (err: unknown) {
166
+ utils.response.send(res, 503, { code: utils.response.code.DB_Action_ERR, message: (err as Error).message });
84
167
  }
85
168
  }
86
- }
169
+ }
170
+
171
+ export default VexDbConnector;
@@ -1,35 +1,34 @@
1
1
  // {{headerComment}}
2
- import { Request, Response } from "express";
2
+ import { Request, Response, NextFunction } from "express";
3
3
  import utils from "./../_utils";
4
+ import VexResponse from "../_types/VexResponse.gen";
4
5
  import VexResponseError from "../_types/VexResponseError.gen";
5
6
 
6
7
  export default class VexSystem {
7
-
8
- constructor() {
9
- // Bind the middleware method to the instance
10
- this.RouteHandler = this.RouteHandler.bind(this);
11
- }
12
8
 
13
9
  /**
14
- * System Middleware
15
- * Feature:
16
- * - error handling
17
- **/
18
- public RouteHandler(req: Request, res: Response, handler: (req: Request, res: Response) => any) {
19
- return handler(req, res).catch((err: any) => {
20
-
21
- if ( err instanceof VexResponseError ) {
22
- return utils.response.send(res, err.status, {
23
- code: err.ret_code,
24
- message: err.message
25
- });
26
- }
27
- else {
28
- return utils.response.send(res, 500, {
29
- code: utils.response.code.SERVER_ERROR,
30
- message: err.message || "Internal Server Error"
31
- });
32
- }
33
- });
10
+ * Express error-handling middleware.
11
+ * Register AFTER all routes: app.use(VexSystem.responseHandler)
12
+ */
13
+ static responseHandler(err: unknown, _req: Request, res: Response, _next: NextFunction): Response {
14
+ if (err instanceof VexResponse) {
15
+ return utils.response.send(res, err.status, err.body);
16
+ }
17
+ else if (err instanceof VexResponseError) {
18
+ const vexErr = err as VexResponseError;
19
+ return utils.response.send(res, vexErr.status, {
20
+ code: vexErr.ret_code,
21
+ message: vexErr.message,
22
+ });
23
+ }
24
+ else {
25
+ utils.log.error("Unhandled error:", err);
26
+ const e: any = err;
27
+ return utils.response.send(res, e?.status ?? 500, {
28
+ code: e?.ret_code ?? utils.response.code.SERVER_ERROR,
29
+ message: e?.message ?? "Internal Server Error",
30
+ });
31
+ }
34
32
  }
33
+
35
34
  }