very-express 0.5.25 → 0.5.26

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.
@@ -1,6 +1,8 @@
1
1
  APP_HOST=http://localhost
2
2
  APP_PORT=3000
3
3
  MONGODB_URI=mongodb://localhost:27017/veryExpressDB
4
+ SQL_URI=postgresql://username:password@localhost:5432/mydatabase
5
+ SQL_CA=""
4
6
 
5
7
  LOGIN_SUCCESS_REDIRECT_PATH=/logincallback
6
8
  LOGIN_FAILED_REDIRECT_PATH=/logincallback
@@ -1,50 +1,54 @@
1
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
- }
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
+ "@types/pg": "^8.20.0",
12
+ "cookie": "^0.6.0",
13
+ "cookie-parser": "^1.4.6",
14
+ "dotenv": "^16.4.4",
15
+ "express": "^4.18.2",
16
+ "express-validator": "^7.0.1",
17
+ "helmet": "^7.1.0",
18
+ "js-yaml": "^4.1.0",
19
+ "jsonwebtoken": "^9.0.2",
20
+ "knex": "^3.2.9",
21
+ "mongo-ts-querystring": "^1.0.4",
22
+ "mongodb": "^5.6.0",
23
+ "mongoose": "^7.4.0",
24
+ "mysql2": "^3.22.0",
25
+ "passport": "^0.7.0",
26
+ "passport-github": "^1.1.0",
27
+ "passport-google-oauth20": "^2.0.0",
28
+ "passport-jwt": "^4.0.1",
29
+ "pg": "^8.20.0",
30
+ "swagger-ui-express": "^5.0.0"
31
+ },
32
+ "devDependencies": {
33
+ "@types/cookie-parser": "^1.4.7",
34
+ "@types/crypto-js": "^4.1.2",
35
+ "@types/dotenv": "^8.2.0",
36
+ "@types/express": "^4.17.17",
37
+ "@types/express-validator": "^3.0.0",
38
+ "@types/js-yaml": "^4.0.9",
39
+ "@types/jsonwebtoken": "^9.0.7",
40
+ "@types/mongodb": "^4.0.7",
41
+ "@types/ms": "^2.1.0",
42
+ "@types/node": "^20.4.2",
43
+ "@types/passport": "^1.0.16",
44
+ "@types/passport-github": "^1.1.12",
45
+ "@types/passport-google-oauth20": "^2.0.14",
46
+ "@types/sequelize": "^4.28.15",
47
+ "@types/swagger-ui-express": "^4.1.6",
48
+ "@types/ws": "^8.5.5",
49
+ "nodemon": "^2.0.22",
50
+ "strip-json-comments": "^5.0.1",
51
+ "ts-node": "^10.9.1",
52
+ "typescript": "^5.1.6"
53
+ }
54
+ }
@@ -1,33 +1,51 @@
1
1
  // {{headerComment}}
2
2
  import mongoose from "mongoose";
3
3
  import { Request, Response, NextFunction } from "express";
4
+ import knex, { Knex } from "knex";
4
5
  import utils from "./../_utils";
5
6
 
6
7
  export default class VexDbConnector {
7
8
  private mongoUrl: string;
8
9
  private sqlUrl: string;
9
10
 
11
+ private sqlConnection?: Knex;
12
+ private sqlClient?: string;
13
+ private sqlCa: string;
10
14
  private recordAccessLog: boolean = false;
11
15
 
12
16
  constructor(options:{
13
17
  mongoUrl?: string;
14
18
  sqlUrl?: string;
19
+ sqlCa?: string;
15
20
  recordAccessLog?: boolean;
16
21
  }){
17
22
  this.mongoUrl = options.mongoUrl || "";
18
23
  this.sqlUrl = options.sqlUrl || "";
24
+ this.sqlCa = options.sqlCa || "";
19
25
  this.recordAccessLog = options.recordAccessLog || false;
20
26
 
21
27
  // Bind the middleware method to the instance
22
28
  this.middleware = this.middleware.bind(this);
23
29
  }
24
30
 
31
+ connect(): void {
32
+ if (this.mongoUrl) this.connectMongo();
33
+ if (this.sqlUrl) this.connectSql();
34
+ }
35
+
36
+ close(): void {
37
+ if (this.mongoUrl) this.closeMongo();
38
+ if (this.sqlUrl) this.closeSql();
39
+ }
25
40
 
26
41
  connectMongo() : mongoose.Connection | void {
27
42
  if ( !this.mongoUrl ){
28
43
  utils.log.error("VexDbConnector : MongoUrl is not invalid");
29
44
  return;
30
45
  }
46
+ else {
47
+ utils.log.infoMongo("Connecting to MongoDB...");
48
+ }
31
49
  /**
32
50
  * @param retryTime time in second
33
51
  */
@@ -55,32 +73,154 @@ export default class VexDbConnector {
55
73
  return mongoose.connection;
56
74
  }
57
75
 
76
+ connectSql(): Knex | void {
77
+ if (!this.sqlUrl) {
78
+ return;
79
+ }
80
+ else {
81
+ utils.log.infoSql("Connecting to SQL DB...");
82
+ }
83
+
84
+ const url = this.sqlUrl.toLowerCase();
85
+ if (url.startsWith("postgres://") || url.startsWith("postgresql://")) {
86
+ this.sqlClient = "pg";
87
+ } else if (url.startsWith("mysql://") || url.startsWith("mariadb://")) {
88
+ this.sqlClient = "mysql2";
89
+ } else {
90
+ // try to guess by common keywords
91
+ if (url.indexOf("postgres") !== -1) this.sqlClient = "pg";
92
+ else this.sqlClient = "mysql2";
93
+ }
94
+
95
+ try {
96
+ const caRaw = this.sqlCa || undefined;
97
+ let ca: string | undefined;
98
+ if (caRaw) {
99
+ ca = caRaw.startsWith("-----BEGIN") ? caRaw : Buffer.from(caRaw, "base64").toString("utf8");
100
+ }
101
+ const insecure = (process.env.SQL_INSECURE_TLS || "").toLowerCase() === "true";
102
+ const ssl = insecure ? { rejectUnauthorized: false } : (ca ? { rejectUnauthorized: true, ca } : undefined);
103
+
104
+ utils.log.infoSql(`Using SQL client: ${this.sqlClient}, SSL: ${ssl ? "enabled" : "disabled"}`);
105
+ const connection: Knex.Config["connection"] | string = this.sqlClient === "pg" ? {
106
+ user: new URL(this.sqlUrl).username,
107
+ password: new URL(this.sqlUrl).password,
108
+ host: new URL(this.sqlUrl).hostname,
109
+ port: Number(new URL(this.sqlUrl).port),
110
+ database: new URL(this.sqlUrl).pathname.slice(1),
111
+ ssl
112
+ } : this.sqlUrl;
113
+
114
+ this.sqlConnection = knex({
115
+ client: this.sqlClient,
116
+ connection,
117
+ pool: { min: 0, max: 10 }
118
+ });
119
+
120
+ // quick health check
121
+ this.sqlConnection.raw("select 1").then(() => {
122
+ utils.log.infoSql("SQL DB Connection established");
123
+ })
124
+ .catch((err:any) => {
125
+ utils.log.errorSql("Failed to establish SQL DB connection", err);
126
+ });
127
+
128
+ return this.sqlConnection;
129
+ }
130
+ catch (err:any) {
131
+ utils.log.errorSql("VexDbConnector: connectSql error", err);
132
+ return;
133
+ }
134
+ }
135
+
136
+ closeMongo(): void {
137
+ if (mongoose.connection.readyState === 1) {
138
+ mongoose.connection.close().then(() => {
139
+ utils.log.infoMongo("MongoDB Connection closed");
140
+ }).catch((err:any) => {
141
+ utils.log.errorMongo("Error closing MongoDB connection", err);
142
+ });
143
+ }
144
+ }
145
+
146
+ closeSql(): void {
147
+ if (this.sqlConnection) {
148
+ this.sqlConnection.destroy().then(() => {
149
+ utils.log.infoSql("SQL DB Connection closed");
150
+ }).catch((err:any) => {
151
+ utils.log.errorSql("Error closing SQL DB connection", err);
152
+ });
153
+ }
154
+ }
155
+
58
156
  /**
59
157
  * Database Middleware
60
158
  * Feature:
61
159
  * - restrict access to app when DB connection down.
62
160
  * - record access log
63
161
  **/
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
- });
69
- }
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
- });
162
+ async middleware(req: Request, res: Response, next: NextFunction): Promise<void> {
163
+ try {
164
+ if (this.mongoUrl && mongoose.connection.readyState !== 1) {
165
+ utils.response.send(res, 503, { code: utils.response.code.DB_CONN_ERR });
166
+ return;
167
+ }
168
+
169
+ if (this.sqlUrl && this.sqlConnection) {
170
+ try {
171
+ await this.sqlConnection.raw("select 1");
172
+ }
173
+ catch (err:any) {
174
+ utils.response.send(res, 503, { code: utils.response.code.DB_CONN_ERR });
175
+ return;
176
+ }
177
+ }
178
+
179
+ if (this.recordAccessLog) {
180
+ const logEntry = {
181
+ timestamp: new Date().getTime(),
182
+ ipa: req.socket.remoteAddress || req.headers["x-forwarded-for"],
183
+ method: req.method,
184
+ url: req.url.split("?")[0],
185
+ headers: req.headers,
186
+ query: req.query,
187
+ } as any;
188
+
189
+ // write to Mongo if available
190
+ if (this.mongoUrl && mongoose.connection.readyState === 1) {
191
+ try {
192
+ mongoose.connection.collection("accessLogs").insertOne(logEntry);
193
+ }
194
+ catch (e:any) {
195
+ utils.log.error("Failed to write access log to Mongo", e);
196
+ }
197
+ }
198
+
199
+ // write to SQL if available
200
+ if (this.sqlUrl && this.sqlConnection) {
201
+ try {
202
+ const table = "accessLogs";
203
+ const insert = { ...logEntry };
204
+ // knex may not accept headers/query objects directly for some DBs,
205
+ // so stringify them to be safe
206
+ insert.headers = JSON.stringify(insert.headers || {});
207
+ insert.query = JSON.stringify(insert.query || {});
208
+ await this.sqlConnection(table).insert(insert as any).catch(()=>{});
209
+ }
210
+ catch (e:any) {
211
+ utils.log.error("Failed to write access log to SQL", e);
212
+ }
213
+ }
214
+
215
+ next();
216
+ return;
217
+ }
218
+
80
219
  next();
81
220
  }
82
- else{
83
- next();
221
+ catch (err:any) {
222
+ utils.response.send(res, 503, { code: utils.response.code.DB_Action_ERR, message: err.message });
84
223
  }
85
224
  }
86
- }
225
+ }
226
+
@@ -2,6 +2,8 @@
2
2
  import { Request, Response } from "express";
3
3
  import utils from "./../_utils";
4
4
  import VexResponseError from "../_types/VexResponseError.gen";
5
+ import VexResponsePayloadError from "../_types/VexResponsePayloadError.gen";
6
+ import { validationResult } from "express-validator";
5
7
 
6
8
  export default class VexSystem {
7
9
 
@@ -11,25 +13,39 @@ export default class VexSystem {
11
13
  }
12
14
 
13
15
  /**
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
- });
16
+ * System Middleware
17
+ * Feature:
18
+ * - error handling
19
+ * - validation handling
20
+ **/
21
+ public RouteHandler(handler: (req: Request, res: Response) => Promise<any>) {
22
+ return async (req: Request, res: Response) => {
23
+ try {
24
+ const validation = validationResult(req);
25
+ if (!validation.isEmpty()) throw new VexResponsePayloadError(validation.array());
26
+ return await handler(req, res);
26
27
  }
27
- else {
28
- return utils.response.send(res, 500, {
29
- code: utils.response.code.SERVER_ERROR,
30
- message: err.message || "Internal Server Error"
31
- });
28
+ catch (err: any) {
29
+ if ( err instanceof VexResponseError ) {
30
+ return utils.response.send(res, err.status, {
31
+ code: err.ret_code,
32
+ message: err.message
33
+ });
34
+ }
35
+ else if (err instanceof VexResponsePayloadError) {
36
+ return utils.response.send(res, err.status, {
37
+ code: err.ret_code,
38
+ message: err.message,
39
+ result: err.result
40
+ });
41
+ }
42
+ else {
43
+ return utils.response.send(res, 500, {
44
+ code: utils.response.code.SERVER_ERROR,
45
+ message: err.message || "Internal Server Error"
46
+ });
47
+ }
32
48
  }
33
- });
49
+ };
34
50
  }
35
51
  }
@@ -0,0 +1,20 @@
1
+ import { ResponseCode } from "../_utils/response.gen";
2
+ import utils from "../_utils/index";
3
+
4
+ export default class VexResponsePayloadError extends Error {
5
+ public status: number;
6
+ public ret_code: ResponseCode;
7
+ public ret_msg: any;
8
+ public result: any;
9
+
10
+ constructor(
11
+ result?: any
12
+ ) {
13
+ super(utils.response.msg.err_payload);
14
+ this.name = "VexResponsePayloadError";
15
+ this.status = 400;
16
+ this.ret_code = utils.response.code.err_payload;
17
+ this.ret_msg = utils.response.msg.err_payload;
18
+ this.result = result;
19
+ }
20
+ }
@@ -36,8 +36,8 @@ export function infoSql(msg: any, ...optionalParams: any[]): void {
36
36
  info("[SQL]", msg, optionalParams);
37
37
  }
38
38
 
39
- export function errorSql(msg: any, ...optionalParams: any[]): never {
40
- error("[SQL]", msg, optionalParams);
39
+ export function errorSql(msg: any, ...optionalParams: any[]): void {
40
+ errorNoExit("[SQL]", msg, optionalParams);
41
41
  }
42
42
 
43
43
  export default {
@@ -1,12 +1,18 @@
1
1
  {
2
2
  "compilerOptions": {
3
3
  /* Visit https://aka.ms/tsconfig to read more about this file */
4
-
4
+
5
+ "baseUrl": ".",
6
+ "paths": {
7
+ "@": ["src"],
8
+ "@/*": ["src/*"]
9
+ },
10
+
5
11
  /* Language and Environment */
6
12
  "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
7
13
 
8
14
  /* Modules */
9
- "module": "commonjs", /* Specify what module code is generated. */
15
+ "module": "commonjs",
10
16
 
11
17
  /* Emit */
12
18
  "outDir": "./dist", /* Specify an output folder for all emitted files. */
@@ -0,0 +1,9 @@
1
+ # future Plan
2
+
3
+ ## security
4
+ - [ ] Rate Limiting
5
+ - [ ] db fields encryption
6
+
7
+ ## features supports
8
+ - [ ] controller extendable, support customisation based on vex generated controller.
9
+ - [ ] [tsoa](https://tsoa-community.github.io/docs/) make it nextjs like and support opanapi with custom endpoint (non generated).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "very-express",
3
- "version": "0.5.25",
3
+ "version": "0.5.26",
4
4
  "description": "based on json schema and openapi, generate Express RestApi server with mongoDb ",
5
5
  "author": "Justin26l",
6
6
  "license": "MIT",
@@ -13,7 +13,10 @@
13
13
  "dev": "npm run compile && npm run start",
14
14
  "build": "npm run lint && npm run compile",
15
15
  "lint": "eslint ./src --ext .ts --fix",
16
- "compile": "node ./scripts/build.js && node ./scripts/copyTsTemplates.js"
16
+ "compile": "node ./scripts/build.js && node ./scripts/copyTsTemplates.js",
17
+ "preversion": "npm run lint",
18
+ "postversion": "npm run compile",
19
+ "v": "node scripts/bump-version.js"
17
20
  },
18
21
  "keywords": [
19
22
  "jsonSchema",
@@ -33,6 +36,7 @@
33
36
  "@types/ms": "^2.1.0",
34
37
  "@types/node": "^20.10.5",
35
38
  "@types/passport": "^1.0.16",
39
+ "@types/pg": "^8.20.0",
36
40
  "@typescript-eslint/eslint-plugin": "^6.18.1",
37
41
  "@typescript-eslint/parser": "^6.18.1",
38
42
  "diff-match-patch": "^1.0.5",
@@ -43,8 +47,11 @@
43
47
  "json-schema-to-openapi-schema": "^0.4.0",
44
48
  "json-schema-to-typescript": "^13.1.1",
45
49
  "json2mongoose": "^0.4.8",
50
+ "knex": "^3.2.9",
46
51
  "minimist": "^1.2.8",
47
52
  "mongoose": "^8.7.1",
53
+ "mysql2": "^3.22.0",
54
+ "pg": "^8.20.0",
48
55
  "ts-node": "^10.9.2",
49
56
  "typescript": "^5.3.3"
50
57
  }
@@ -0,0 +1,87 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'url';
4
+ import { execSync } from 'child_process';
5
+
6
+ function bumpVersion(mode, devNum, major, minor, patch) {
7
+ let newVersion;
8
+ if (mode === 'dev') {
9
+ if (devNum) {
10
+ newVersion = `${major}.${minor}.${patch}-dev${parseInt(devNum) + 1}`;
11
+ } else {
12
+ newVersion = `${major}.${minor}.${patch}-dev1`;
13
+ }
14
+ } else if (mode === 'patch') {
15
+ patch += 1;
16
+ newVersion = `${major}.${minor}.${patch}`;
17
+ } else if (mode === 'minor') {
18
+ minor += 1;
19
+ patch = 0;
20
+ newVersion = `${major}.${minor}.${patch}`;
21
+ } else if (mode === 'major') {
22
+ major += 1;
23
+ minor = 0;
24
+ patch = 0;
25
+ newVersion = `${major}.${minor}.${patch}`;
26
+ } else {
27
+ console.error('\x1b[31m', `Invalid version mode "${mode}", no version applied`);
28
+ process.exit(0);
29
+ };
30
+ return newVersion;
31
+ };
32
+
33
+ function main() {
34
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
35
+ const pkgPath = path.resolve(__dirname, '../package.json');
36
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
37
+
38
+ const mode = process.env.npm_config_version_type || process.argv[2] || 'none';
39
+
40
+ const versionMatch = pkg.version.match(/^(\d+)\.(\d+)\.(\d+)(-dev(\d+))?$/);
41
+ if (!versionMatch) {
42
+ console.error('\x1b[31m', `Invalid version "${pkg.version}", Version must be in the form x.y.z or x.y.z-devN, no version applied`);
43
+ process.exit(0);
44
+ };
45
+
46
+ let [_, major, minor, patch, devFull, devNum] = versionMatch;
47
+ major = parseInt(major);
48
+ minor = parseInt(minor);
49
+ patch = parseInt(patch);
50
+
51
+ // Run preversion
52
+ if (pkg.scripts && pkg.scripts.preversion) {
53
+ try {
54
+ execSync(pkg.scripts.preversion, { stdio: 'inherit' });
55
+ } catch (e) {
56
+ console.warn('preversion script failed:', e.message);
57
+ process.exit(1);
58
+ }
59
+ };
60
+
61
+ // Bump version
62
+ const newVersion = bumpVersion(mode, devNum, major, minor, patch);
63
+ pkg.version = newVersion;
64
+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 4) + '\n');
65
+ console.log(`Bumped version (${mode}) to`, newVersion);
66
+
67
+ // Run postversion
68
+ if (pkg.scripts && pkg.scripts.postversion) {
69
+ try {
70
+ execSync(pkg.scripts.postversion, { stdio: 'inherit' });
71
+ } catch (e) {
72
+ console.warn('postversion script failed:', e.message);
73
+ process.exit(1);
74
+ }
75
+ };
76
+
77
+ // Add git tag for versioning
78
+ try {
79
+ execSync(`git commit -am "v${newVersion}"`);
80
+ execSync(`git tag v${newVersion}`);
81
+ console.log(`Created git tag v${newVersion}`);
82
+ } catch (e) {
83
+ console.warn('Failed to create git tag:', e.message);
84
+ }
85
+ };
86
+
87
+ main();
@@ -1,5 +0,0 @@
1
- # v0.7.0 Plan
2
-
3
- ## security
4
- - [ ] Rate Limiting
5
- - [ ] db fields encryption