kool-koala 1.7.1 → 1.7.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.
- package/common/koalapp.d.ts +8 -8
- package/common/koalapp.js +29 -13
- package/common/koalapp.js.map +1 -1
- package/database/repositories/repository-base.d.ts +4 -4
- package/database/repositories/repository-base.js +6 -4
- package/database/repositories/repository-base.js.map +1 -1
- package/database/repositories/soft-deletable-repository-base.d.ts +1 -1
- package/database/repositories/soft-deletable-repository-base.js +9 -4
- package/database/repositories/soft-deletable-repository-base.js.map +1 -1
- package/package.json +10 -7
package/common/koalapp.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { Next } from
|
|
2
|
-
import { Configuration } from
|
|
3
|
-
import { RouterService } from
|
|
4
|
-
import { AuthenticableEntity } from
|
|
5
|
-
import { DataSource } from
|
|
6
|
-
import { AuthorizationService } from
|
|
7
|
-
import { StringEnum } from
|
|
8
|
-
import { Context } from
|
|
1
|
+
import { Next } from "koa";
|
|
2
|
+
import { Configuration } from "./configuration";
|
|
3
|
+
import { RouterService } from "../services/router-service";
|
|
4
|
+
import { AuthenticableEntity } from "../types/entities/authenticable-entity";
|
|
5
|
+
import { DataSource } from "typeorm";
|
|
6
|
+
import { AuthorizationService } from "../services";
|
|
7
|
+
import { StringEnum } from "../types/common/string-enum";
|
|
8
|
+
import { Context } from "../types/common/context";
|
|
9
9
|
export declare class KoalApp<U extends AuthenticableEntity, P extends StringEnum> {
|
|
10
10
|
private configuration;
|
|
11
11
|
private static instance;
|
package/common/koalapp.js
CHANGED
|
@@ -74,14 +74,16 @@ class KoalApp {
|
|
|
74
74
|
}
|
|
75
75
|
catch (error) {
|
|
76
76
|
console.log("Error during database initialization...", error);
|
|
77
|
-
throw new Error(
|
|
77
|
+
throw new Error("Error during application intialization...");
|
|
78
78
|
}
|
|
79
79
|
});
|
|
80
80
|
}
|
|
81
81
|
setupDatabaseConnection() {
|
|
82
82
|
return __awaiter(this, void 0, void 0, function* () {
|
|
83
83
|
if (this.configuration.getDatabase()) {
|
|
84
|
-
this.databaseConnection = yield this.configuration
|
|
84
|
+
this.databaseConnection = yield this.configuration
|
|
85
|
+
.getDatabase()
|
|
86
|
+
.dataSource.initialize();
|
|
85
87
|
yield this.databaseConnection.runMigrations();
|
|
86
88
|
}
|
|
87
89
|
});
|
|
@@ -103,33 +105,47 @@ class KoalApp {
|
|
|
103
105
|
if (!configs)
|
|
104
106
|
return;
|
|
105
107
|
this.koa.use((ctx, next) => __awaiter(this, void 0, void 0, function* () {
|
|
106
|
-
var _a, _b;
|
|
108
|
+
var _a, _b, _c, _d;
|
|
107
109
|
const requestPath = ctx.request.path.replace(/^\//, "");
|
|
108
110
|
let fileServed = false;
|
|
109
111
|
for (const staticFilesConfig of configs) {
|
|
110
112
|
const staticFilesPath = path_1.default.isAbsolute(staticFilesConfig.folder)
|
|
111
113
|
? staticFilesConfig.folder
|
|
112
114
|
: path_1.default.join(path_1.default.dirname(require.main.filename), staticFilesConfig.folder);
|
|
113
|
-
console.log(`Checking static files in: ${staticFilesPath}`);
|
|
114
115
|
const filePath = path_1.default.join(staticFilesPath, requestPath);
|
|
115
116
|
if (fs_1.default.existsSync(filePath) && fs_1.default.statSync(filePath).isFile()) {
|
|
116
|
-
ctx.type =
|
|
117
|
+
ctx.type =
|
|
118
|
+
path_1.default.extname(filePath).slice(1) || "application/octet-stream";
|
|
117
119
|
const stat = fs_1.default.statSync(filePath);
|
|
118
120
|
ctx.set("Content-Length", stat.size.toString());
|
|
119
121
|
ctx.body = fs_1.default.createReadStream(filePath);
|
|
120
122
|
fileServed = true;
|
|
121
123
|
break;
|
|
122
124
|
}
|
|
125
|
+
if (fs_1.default.existsSync(filePath) && fs_1.default.statSync(filePath).isDirectory()) {
|
|
126
|
+
const defaultFile = (_a = staticFilesConfig.defaultFile) !== null && _a !== void 0 ? _a : "index.html";
|
|
127
|
+
const indexFilePath = path_1.default.join(filePath, defaultFile);
|
|
128
|
+
if (fs_1.default.existsSync(indexFilePath) &&
|
|
129
|
+
fs_1.default.statSync(indexFilePath).isFile()) {
|
|
130
|
+
ctx.type = (_b = staticFilesConfig.defaultFileMimeType) !== null && _b !== void 0 ? _b : "text/html";
|
|
131
|
+
const stat = fs_1.default.statSync(indexFilePath);
|
|
132
|
+
ctx.set("Content-Length", stat.size.toString());
|
|
133
|
+
ctx.body = fs_1.default.createReadStream(indexFilePath);
|
|
134
|
+
fileServed = true;
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
123
138
|
}
|
|
124
139
|
if (!fileServed) {
|
|
125
140
|
for (const staticFilesConfig of configs) {
|
|
126
141
|
const staticFilesPath = path_1.default.isAbsolute(staticFilesConfig.folder)
|
|
127
142
|
? staticFilesConfig.folder
|
|
128
143
|
: path_1.default.join(path_1.default.dirname(require.main.filename), staticFilesConfig.folder);
|
|
129
|
-
const defaultFile = (
|
|
144
|
+
const defaultFile = (_c = staticFilesConfig.defaultFile) !== null && _c !== void 0 ? _c : "index.html";
|
|
130
145
|
const defaultFilePath = path_1.default.join(staticFilesPath, defaultFile);
|
|
131
|
-
if (fs_1.default.existsSync(defaultFilePath) &&
|
|
132
|
-
|
|
146
|
+
if (fs_1.default.existsSync(defaultFilePath) &&
|
|
147
|
+
fs_1.default.statSync(defaultFilePath).isFile()) {
|
|
148
|
+
ctx.type = (_d = staticFilesConfig.defaultFileMimeType) !== null && _d !== void 0 ? _d : "text/html";
|
|
133
149
|
const stat = fs_1.default.statSync(defaultFilePath);
|
|
134
150
|
ctx.set("Content-Length", stat.size.toString());
|
|
135
151
|
ctx.body = fs_1.default.createReadStream(defaultFilePath);
|
|
@@ -179,16 +195,16 @@ class KoalApp {
|
|
|
179
195
|
return __awaiter(this, void 0, void 0, function* () {
|
|
180
196
|
const authHeader = context.headers.authorization;
|
|
181
197
|
if (authHeader) {
|
|
182
|
-
const token = authHeader.split(
|
|
198
|
+
const token = authHeader.split(" ")[1];
|
|
183
199
|
try {
|
|
184
|
-
context.state.user = jsonwebtoken_1.default.verify(token, this.configuration.getJwtParameters().secretKey);
|
|
200
|
+
context.state.user = (jsonwebtoken_1.default.verify(token, this.configuration.getJwtParameters().secretKey));
|
|
185
201
|
yield next();
|
|
186
202
|
}
|
|
187
203
|
catch (error) {
|
|
188
204
|
context.status = status_code_1.StatusCode.UNAUTHORIZED;
|
|
189
205
|
context.body = {
|
|
190
206
|
success: false,
|
|
191
|
-
message:
|
|
207
|
+
message: "Invalid token",
|
|
192
208
|
};
|
|
193
209
|
}
|
|
194
210
|
}
|
|
@@ -207,14 +223,14 @@ class KoalApp {
|
|
|
207
223
|
context.status = error.getStatusCode();
|
|
208
224
|
context.body = {
|
|
209
225
|
success: false,
|
|
210
|
-
message: error.message
|
|
226
|
+
message: error.message,
|
|
211
227
|
};
|
|
212
228
|
}
|
|
213
229
|
else {
|
|
214
230
|
console.log(error);
|
|
215
231
|
context.status = status_code_1.StatusCode.INTERNAL_SERVER_ERROR;
|
|
216
232
|
context.body = {
|
|
217
|
-
success: false
|
|
233
|
+
success: false,
|
|
218
234
|
};
|
|
219
235
|
}
|
|
220
236
|
}
|
package/common/koalapp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/../src/common/koalapp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,8CAAgC;AAEhC,+DAA2D;AAG3D,+CAA2C;AAC3C,gEAA+B;AAC/B,oEAAwC;AACxC,oCAAmD;AACnD,gDAAwB;AACxB,4CAAoB;AAGpB,sFAAiF;AACjF,kFAA8E;AAI9E,MAAa,OAAO;IAclB,YAA4B,aAAkC;QAAlC,kBAAa,GAAb,aAAa,CAAqB;QARtD,QAAG,GAAG,IAAI,aAAG,EAAE,CAAC;IASxB,CAAC;IAEM,MAAM,CAAC,WAAW,CAGvB,aAAmC;QACnC,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;YACtB,IAAI,CAAC,aAAa,EAAE,CAAC;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G,MAAM,IAAI,EAAE,CAAC;gBACf,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,OAAO,CAAC,MAAM,GAAG,wBAAU,CAAC,YAAY,CAAC;oBACzC,OAAO,CAAC,IAAI,GAAG;wBACb,OAAO,EAAE,KAAK;wBACd,OAAO,EAAE,eAAe;qBACzB,CAAA;gBACH,CAAC;YACH,CAAC;iBACI,CAAC;gBACJ,MAAM,IAAI,EAAE,CAAC;YACf,CAAC;QACH,CAAC;KAAA;IAEK,YAAY,CAAC,OAAgB,EAAE,IAAU;;YAC7C,IAAI,CAAC;gBACH,MAAM,IAAI,EAAE,CAAC;YACf,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,KAAK,YAAY,iBAAS,EAAE,CAAC;oBAC/B,OAAO,CAAC,MAAM,GAAG,KAAK,CAAC,aAAa,EAAE,CAAC;oBACvC,OAAO,CAAC,IAAI,GAAiB;wBAC3B,OAAO,EAAE,KAAK;wBACd,OAAO,EAAE,KAAK,CAAC,OAAO;qBACvB,CAAC;gBACJ,CAAC;qBACI,CAAC;oBACJ,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;oBACnB,OAAO,CAAC,MAAM,GAAG,wBAAU,CAAC,qBAAqB,CAAC;oBAClD,OAAO,CAAC,IAAI,GAAiB;wBAC3B,OAAO,EAAE,KAAK;qBACf,CAAC;gBACJ,CAAC;YACH,CAAC;QACH,CAAC;KAAA;IAED,uBAAuB;QACrB,OAAO,IAAI,CAAC,oBAAoB,CAAC;IACnC,CAAC;CACF;AA3ND,0BA2NC","file":"koalapp.js","sourcesContent":["import Koa, { Next } from 'koa';\nimport { Configuration } from './configuration';\nimport { RouterService } from '../services/router-service';\nimport { AuthenticableEntity } from '../types/entities/authenticable-entity';\nimport { DataSource } from 'typeorm';\nimport { StatusCode } from './status-code';\nimport jwt from 'jsonwebtoken';\nimport bodyParser from 'koa-bodyparser';\nimport { BaseResponse, ErrorBase } from '../types';\nimport path from \"path\";\nimport fs from \"fs\";\nimport { AuthorizationService } from '../services';\nimport { StringEnum } from '../types/common/string-enum';\nimport { errorHandlerMiddleware } from '../middlewares/error-handler-middleware';\nimport { transactionMiddleware } from '../middlewares/transaction-middleware';\nimport { Server } from 'http';\nimport { Context } from '../types/common/context';\n\nexport class KoalApp<\n U extends AuthenticableEntity,\n P extends StringEnum\n> {\n private static instance: KoalApp<any, any>;\n\n private koa = new Koa();\n private routerService: RouterService;\n private databaseConnection: DataSource;\n\n private server: Server;\n\n private authorizationService: AuthorizationService<U, P>;\n\n private constructor(private configuration: Configuration<U, P>) {\n }\n\n public static getInstance<\n T extends AuthenticableEntity,\n Q extends StringEnum\n >(configuration?: Configuration<T, Q>): KoalApp<T, Q> {\n if (!KoalApp.instance) {\n if (!configuration) {\n throw new Error(\"Configuration is required\");\n }\n KoalApp.instance = new KoalApp(configuration!);\n }\n return KoalApp.instance;\n }\n\n public static async resetInstance() {\n await KoalApp.getInstance().getDatabaseConnection().destroy();\n KoalApp.instance = undefined;\n }\n\n public getConfiguration(): Configuration<U, P> {\n return this.configuration;\n }\n\n public getRouterService(): RouterService {\n return this.routerService;\n }\n\n public getDatabaseConnection(): DataSource {\n return this.databaseConnection;\n }\n async initialize() {\n try {\n await this.setupDatabaseConnection();\n console.log(\"Database connection initialized.\");\n this.setupErrorHandler();\n console.log(\"Error handler initialized.\");\n this.setupTransaction();\n console.log(\"Transaction starter middleware initialized.\");\n this.koa.use(this.authorizationHeaderParser.bind(this));\n console.log(\"Authorization header parser initialized.\");\n this.koa.use(bodyParser());\n console.log(\"Body parser initialized.\");\n this.registerMiddlewaresFromConfiguration();\n console.log(\"Middlewares registered from configuration.\");\n this.registerEndpoints();\n console.log(\"Endpoints registered.\");\n this.registerStaticFileServerMiddleware();\n console.log(\"Static file server initialized.\");\n } catch (error) {\n console.log(\"Error during database initialization...\", error);\n throw new Error('Error during application intialization...');\n }\n }\n async setupDatabaseConnection() {\n if (this.configuration.getDatabase()) {\n this.databaseConnection = await this.configuration.getDatabase().dataSource.initialize();\n await this.databaseConnection.runMigrations();\n }\n }\n setupErrorHandler() {\n this.koa.use(errorHandlerMiddleware);\n }\n setupTransaction() {\n this.koa.use(transactionMiddleware);\n }\n\n registerEndpoints() {\n this.routerService = new RouterService(\n this.configuration.getControllers()\n );\n this.koa\n .use(this.routerService.getRoutes())\n .use(this.routerService.allowedMethods());\n }\n\n registerStaticFileServerMiddleware() {\n const configs = this.configuration.getStaticFilesConfiguration();\n if (!configs) return;\n\n this.koa.use(async (ctx: Context, next: () => Promise<void>) => {\n const requestPath = ctx.request.path.replace(/^\\//, \"\");\n let fileServed = false;\n\n for (const staticFilesConfig of configs) {\n const staticFilesPath = path.isAbsolute(staticFilesConfig.folder)\n ? staticFilesConfig.folder\n : path.join(path.dirname(require.main.filename), staticFilesConfig.folder);\n console.log(`Checking static files in: ${staticFilesPath}`);\n\n const filePath = path.join(staticFilesPath, requestPath);\n\n if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {\n ctx.type = path.extname(filePath).slice(1) || \"application/octet-stream\";\n const stat = fs.statSync(filePath);\n ctx.set(\"Content-Length\", stat.size.toString());\n ctx.body = fs.createReadStream(filePath);\n fileServed = true;\n break;\n }\n }\n\n if (!fileServed) {\n for (const staticFilesConfig of configs) {\n const staticFilesPath = path.isAbsolute(staticFilesConfig.folder)\n ? staticFilesConfig.folder\n : path.join(path.dirname(require.main.filename), staticFilesConfig.folder);\n const defaultFile = staticFilesConfig.defaultFile ?? \"index.html\";\n const defaultFilePath = path.join(staticFilesPath, defaultFile);\n\n if (fs.existsSync(defaultFilePath) && fs.statSync(defaultFilePath).isFile()) {\n ctx.type = staticFilesConfig.defaultFileMimeType ?? \"text/html\";\n const stat = fs.statSync(defaultFilePath);\n ctx.set(\"Content-Length\", stat.size.toString());\n ctx.body = fs.createReadStream(defaultFilePath);\n fileServed = true;\n break;\n }\n }\n }\n\n if (!fileServed) {\n await next();\n }\n });\n }\n\n registerMiddlewaresFromConfiguration() {\n for (const middleware of this.configuration.getMiddlewares() || []) {\n this.koa.use(middleware);\n }\n }\n\n async start(callback?: (configuration: Configuration<U, P>) => void) {\n this.server = this.koa.listen(this.configuration.getPort(), () => {\n if (callback) {\n callback(this.configuration);\n }\n });\n }\n\n stop() {\n return new Promise<void>((resolve, reject) => {\n if (this.server) {\n this.server.close((error) => {\n if (!error) {\n resolve();\n }\n else {\n reject();\n }\n });\n this.server = undefined;\n }\n else {\n reject();\n }\n });\n }\n\n async authorizationHeaderParser(context: Context, next: Next) {\n const authHeader = context.headers.authorization;\n if (authHeader) {\n const token = authHeader.split(' ')[1];\n try {\n context.state.user = <AuthenticableEntity>jwt.verify(token, this.configuration.getJwtParameters().secretKey);\n await next();\n } catch (error) {\n context.status = StatusCode.UNAUTHORIZED;\n context.body = {\n success: false,\n message: 'Invalid token'\n }\n }\n }\n else {\n await next();\n }\n }\n\n async errorHandler(context: Context, next: Next) {\n try {\n await next();\n } catch (error) {\n if (error instanceof ErrorBase) {\n context.status = error.getStatusCode();\n context.body = <BaseResponse>{\n success: false,\n message: error.message\n };\n }\n else {\n console.log(error);\n context.status = StatusCode.INTERNAL_SERVER_ERROR;\n context.body = <BaseResponse>{\n success: false\n };\n }\n }\n }\n\n getAuthorizationService() {\n return this.authorizationService;\n }\n}"]}
|
|
1
|
+
{"version":3,"sources":["../src/../src/common/koalapp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,8CAAgC;AAEhC,+DAA2D;AAG3D,+CAA2C;AAC3C,gEAA+B;AAC/B,oEAAwC;AACxC,oCAAmD;AACnD,gDAAwB;AACxB,4CAAoB;AAGpB,sFAAiF;AACjF,kFAA8E;AAI9E,MAAa,OAAO;IAWlB,YAA4B,aAAkC;QAAlC,kBAAa,GAAb,aAAa,CAAqB;QARtD,QAAG,GAAG,IAAI,aAAG,EAAE,CAAC;IAQyC,CAAC;IAE3D,MAAM,CAAC,WAAW,CAGvB,aAAmC;QACnC,IAAI,CAAC,OAAO,CAAC,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f,IAAI,KAAK,YAAY,iBAAS,EAAE,CAAC;oBAC/B,OAAO,CAAC,MAAM,GAAG,KAAK,CAAC,aAAa,EAAE,CAAC;oBACvC,OAAO,CAAC,IAAI,GAAiB;wBAC3B,OAAO,EAAE,KAAK;wBACd,OAAO,EAAE,KAAK,CAAC,OAAO;qBACvB,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACN,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;oBACnB,OAAO,CAAC,MAAM,GAAG,wBAAU,CAAC,qBAAqB,CAAC;oBAClD,OAAO,CAAC,IAAI,GAAiB;wBAC3B,OAAO,EAAE,KAAK;qBACf,CAAC;gBACJ,CAAC;YACH,CAAC;QACH,CAAC;KAAA;IAED,uBAAuB;QACrB,OAAO,IAAI,CAAC,oBAAoB,CAAC;IACnC,CAAC;CACF;AA/OD,0BA+OC","file":"koalapp.js","sourcesContent":["import Koa, { Next } from \"koa\";\nimport { Configuration } from \"./configuration\";\nimport { RouterService } from \"../services/router-service\";\nimport { AuthenticableEntity } from \"../types/entities/authenticable-entity\";\nimport { DataSource } from \"typeorm\";\nimport { StatusCode } from \"./status-code\";\nimport jwt from \"jsonwebtoken\";\nimport bodyParser from \"koa-bodyparser\";\nimport { BaseResponse, ErrorBase } from \"../types\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { AuthorizationService } from \"../services\";\nimport { StringEnum } from \"../types/common/string-enum\";\nimport { errorHandlerMiddleware } from \"../middlewares/error-handler-middleware\";\nimport { transactionMiddleware } from \"../middlewares/transaction-middleware\";\nimport { Server } from \"http\";\nimport { Context } from \"../types/common/context\";\n\nexport class KoalApp<U extends AuthenticableEntity, P extends StringEnum> {\n private static instance: KoalApp<any, any>;\n\n private koa = new Koa();\n private routerService: RouterService;\n private databaseConnection: DataSource;\n\n private server: Server;\n\n private authorizationService: AuthorizationService<U, P>;\n\n private constructor(private configuration: Configuration<U, P>) {}\n\n public static getInstance<\n T extends AuthenticableEntity,\n Q extends StringEnum\n >(configuration?: Configuration<T, Q>): KoalApp<T, Q> {\n if (!KoalApp.instance) {\n if (!configuration) {\n throw new Error(\"Configuration is required\");\n }\n KoalApp.instance = new KoalApp(configuration!);\n }\n return KoalApp.instance;\n }\n\n public static async resetInstance() {\n await KoalApp.getInstance().getDatabaseConnection().destroy();\n KoalApp.instance = undefined;\n }\n\n public getConfiguration(): Configuration<U, P> {\n return this.configuration;\n }\n\n public getRouterService(): RouterService {\n return this.routerService;\n }\n\n public getDatabaseConnection(): DataSource {\n return this.databaseConnection;\n }\n async initialize() {\n try {\n await this.setupDatabaseConnection();\n console.log(\"Database connection initialized.\");\n this.setupErrorHandler();\n console.log(\"Error handler initialized.\");\n this.setupTransaction();\n console.log(\"Transaction starter middleware initialized.\");\n this.koa.use(this.authorizationHeaderParser.bind(this));\n console.log(\"Authorization header parser initialized.\");\n this.koa.use(bodyParser());\n console.log(\"Body parser initialized.\");\n this.registerMiddlewaresFromConfiguration();\n console.log(\"Middlewares registered from configuration.\");\n this.registerEndpoints();\n console.log(\"Endpoints registered.\");\n this.registerStaticFileServerMiddleware();\n console.log(\"Static file server initialized.\");\n } catch (error) {\n console.log(\"Error during database initialization...\", error);\n throw new Error(\"Error during application intialization...\");\n }\n }\n async setupDatabaseConnection() {\n if (this.configuration.getDatabase()) {\n this.databaseConnection = await this.configuration\n .getDatabase()\n .dataSource.initialize();\n await this.databaseConnection.runMigrations();\n }\n }\n setupErrorHandler() {\n this.koa.use(errorHandlerMiddleware);\n }\n setupTransaction() {\n this.koa.use(transactionMiddleware);\n }\n\n registerEndpoints() {\n this.routerService = new RouterService(this.configuration.getControllers());\n this.koa\n .use(this.routerService.getRoutes())\n .use(this.routerService.allowedMethods());\n }\n\n registerStaticFileServerMiddleware() {\n const configs = this.configuration.getStaticFilesConfiguration();\n if (!configs) return;\n\n this.koa.use(async (ctx: Context, next: () => Promise<void>) => {\n const requestPath = ctx.request.path.replace(/^\\//, \"\");\n let fileServed = false;\n\n for (const staticFilesConfig of configs) {\n const staticFilesPath = path.isAbsolute(staticFilesConfig.folder)\n ? staticFilesConfig.folder\n : path.join(\n path.dirname(require.main.filename),\n staticFilesConfig.folder\n );\n\n const filePath = path.join(staticFilesPath, requestPath);\n\n if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {\n ctx.type =\n path.extname(filePath).slice(1) || \"application/octet-stream\";\n const stat = fs.statSync(filePath);\n ctx.set(\"Content-Length\", stat.size.toString());\n ctx.body = fs.createReadStream(filePath);\n fileServed = true;\n break;\n }\n\n if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {\n const defaultFile = staticFilesConfig.defaultFile ?? \"index.html\";\n const indexFilePath = path.join(filePath, defaultFile);\n\n if (\n fs.existsSync(indexFilePath) &&\n fs.statSync(indexFilePath).isFile()\n ) {\n ctx.type = staticFilesConfig.defaultFileMimeType ?? \"text/html\";\n const stat = fs.statSync(indexFilePath);\n ctx.set(\"Content-Length\", stat.size.toString());\n ctx.body = fs.createReadStream(indexFilePath);\n fileServed = true;\n break;\n }\n }\n }\n\n if (!fileServed) {\n for (const staticFilesConfig of configs) {\n const staticFilesPath = path.isAbsolute(staticFilesConfig.folder)\n ? staticFilesConfig.folder\n : path.join(\n path.dirname(require.main.filename),\n staticFilesConfig.folder\n );\n const defaultFile = staticFilesConfig.defaultFile ?? \"index.html\";\n const defaultFilePath = path.join(staticFilesPath, defaultFile);\n\n if (\n fs.existsSync(defaultFilePath) &&\n fs.statSync(defaultFilePath).isFile()\n ) {\n ctx.type = staticFilesConfig.defaultFileMimeType ?? \"text/html\";\n const stat = fs.statSync(defaultFilePath);\n ctx.set(\"Content-Length\", stat.size.toString());\n ctx.body = fs.createReadStream(defaultFilePath);\n fileServed = true;\n break;\n }\n }\n }\n\n if (!fileServed) {\n await next();\n }\n });\n }\n\n registerMiddlewaresFromConfiguration() {\n for (const middleware of this.configuration.getMiddlewares() || []) {\n this.koa.use(middleware);\n }\n }\n\n async start(callback?: (configuration: Configuration<U, P>) => void) {\n this.server = this.koa.listen(this.configuration.getPort(), () => {\n if (callback) {\n callback(this.configuration);\n }\n });\n }\n\n stop() {\n return new Promise<void>((resolve, reject) => {\n if (this.server) {\n this.server.close((error) => {\n if (!error) {\n resolve();\n } else {\n reject();\n }\n });\n this.server = undefined;\n } else {\n reject();\n }\n });\n }\n\n async authorizationHeaderParser(context: Context, next: Next) {\n const authHeader = context.headers.authorization;\n if (authHeader) {\n const token = authHeader.split(\" \")[1];\n try {\n context.state.user = <AuthenticableEntity>(\n jwt.verify(token, this.configuration.getJwtParameters().secretKey)\n );\n await next();\n } catch (error) {\n context.status = StatusCode.UNAUTHORIZED;\n context.body = {\n success: false,\n message: \"Invalid token\",\n };\n }\n } else {\n await next();\n }\n }\n\n async errorHandler(context: Context, next: Next) {\n try {\n await next();\n } catch (error) {\n if (error instanceof ErrorBase) {\n context.status = error.getStatusCode();\n context.body = <BaseResponse>{\n success: false,\n message: error.message,\n };\n } else {\n console.log(error);\n context.status = StatusCode.INTERNAL_SERVER_ERROR;\n context.body = <BaseResponse>{\n success: false,\n };\n }\n }\n }\n\n getAuthorizationService() {\n return this.authorizationService;\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DeepPartial, FindManyOptions, FindOneOptions, FindOptionsRelations, FindOptionsWhere, QueryRunner, Repository } from "typeorm";
|
|
1
|
+
import { DeepPartial, DeleteResult, FindManyOptions, FindOneOptions, FindOptionsRelations, FindOptionsWhere, QueryRunner, Repository } from "typeorm";
|
|
2
2
|
import { IdentifiableEntity } from "../../types";
|
|
3
3
|
export declare abstract class RepositoryBase<T extends IdentifiableEntity> {
|
|
4
4
|
private _repository;
|
|
@@ -10,7 +10,7 @@ export declare abstract class RepositoryBase<T extends IdentifiableEntity> {
|
|
|
10
10
|
getOneWhere(options: FindOneOptions<T>): Promise<T>;
|
|
11
11
|
getById(id: number, relations?: FindOptionsRelations<T>): Promise<T>;
|
|
12
12
|
save(entity: T | DeepPartial<T>): Promise<DeepPartial<T> & T>;
|
|
13
|
-
delete(entity: T): Promise<
|
|
14
|
-
deleteWhere(where?: FindOptionsWhere<T>): Promise<
|
|
15
|
-
deleteAll(): Promise<
|
|
13
|
+
delete(entity: T): Promise<DeleteResult>;
|
|
14
|
+
deleteWhere(where?: FindOptionsWhere<T>): Promise<DeleteResult>;
|
|
15
|
+
deleteAll(): Promise<DeleteResult> | Promise<void>;
|
|
16
16
|
}
|
|
@@ -5,7 +5,9 @@ const common_1 = require("../../common");
|
|
|
5
5
|
class RepositoryBase {
|
|
6
6
|
constructor(queryRunner) {
|
|
7
7
|
if (queryRunner === undefined) {
|
|
8
|
-
this._repository = common_1.KoalApp.getInstance()
|
|
8
|
+
this._repository = common_1.KoalApp.getInstance()
|
|
9
|
+
.getDatabaseConnection()
|
|
10
|
+
.getRepository(this.getEntityType());
|
|
9
11
|
}
|
|
10
12
|
else {
|
|
11
13
|
this._repository = queryRunner.manager.getRepository(this.getEntityType());
|
|
@@ -26,9 +28,9 @@ class RepositoryBase {
|
|
|
26
28
|
getById(id, relations) {
|
|
27
29
|
return this.getRepository().findOne({
|
|
28
30
|
where: {
|
|
29
|
-
id
|
|
31
|
+
id,
|
|
30
32
|
},
|
|
31
|
-
relations
|
|
33
|
+
relations,
|
|
32
34
|
});
|
|
33
35
|
}
|
|
34
36
|
save(entity) {
|
|
@@ -41,7 +43,7 @@ class RepositoryBase {
|
|
|
41
43
|
return this.getRepository().delete(where);
|
|
42
44
|
}
|
|
43
45
|
deleteAll() {
|
|
44
|
-
return this.
|
|
46
|
+
return this.getRepository().deleteAll();
|
|
45
47
|
}
|
|
46
48
|
}
|
|
47
49
|
exports.RepositoryBase = RepositoryBase;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/../src/database/repositories/repository-base.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"sources":["../src/../src/database/repositories/repository-base.ts"],"names":[],"mappings":";;;AAWA,yCAAuC;AAEvC,MAAsB,cAAc;IAElC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AC,SAAS,EAAE,CAAC;IAC1C,CAAC;CACF;AA9CD,wCA8CC","file":"repository-base.js","sourcesContent":["import {\n DeepPartial,\n DeleteResult,\n FindManyOptions,\n FindOneOptions,\n FindOptionsRelations,\n FindOptionsWhere,\n QueryRunner,\n Repository,\n} from \"typeorm\";\nimport { IdentifiableEntity } from \"../../types\";\nimport { KoalApp } from \"../../common\";\n\nexport abstract class RepositoryBase<T extends IdentifiableEntity> {\n private _repository: Repository<T>;\n constructor(queryRunner?: QueryRunner) {\n if (queryRunner === undefined) {\n this._repository = KoalApp.getInstance()\n .getDatabaseConnection()\n .getRepository(this.getEntityType());\n } else {\n this._repository = queryRunner.manager.getRepository(\n this.getEntityType()\n );\n }\n }\n getRepository() {\n return this._repository;\n }\n abstract getEntityType(): new () => T;\n getAll() {\n return this._repository.find();\n }\n getWhere(options: FindManyOptions<T>) {\n return this._repository.find(options);\n }\n getOneWhere(options: FindOneOptions<T>) {\n return this._repository.findOne(options);\n }\n getById(id: number, relations?: FindOptionsRelations<T>) {\n return this.getRepository().findOne(<FindOneOptions<T>>{\n where: {\n id,\n },\n relations,\n });\n }\n save(entity: T | DeepPartial<T>) {\n return this.getRepository().save(entity);\n }\n delete(entity: T) {\n return this.getRepository().delete(entity.id);\n }\n deleteWhere(where?: FindOptionsWhere<T>) {\n return this.getRepository().delete(where);\n }\n deleteAll(): Promise<DeleteResult> | Promise<void> {\n return this.getRepository().deleteAll();\n }\n}\n"]}
|
|
@@ -9,5 +9,5 @@ export declare abstract class SoftDeletableRepositoryBase<T extends Identifiable
|
|
|
9
9
|
getById(id: number, relations?: FindOptionsRelations<T>, withDeleted?: boolean): Promise<T>;
|
|
10
10
|
delete(entity: T, hardDelete?: boolean): Promise<DeleteResult>;
|
|
11
11
|
deleteWhere(where?: FindOptionsWhere<T>, hardDelete?: boolean): Promise<DeleteResult>;
|
|
12
|
-
deleteAll(hardDelete?: boolean): Promise<DeleteResult>;
|
|
12
|
+
deleteAll(hardDelete?: boolean): Promise<DeleteResult> | Promise<void>;
|
|
13
13
|
}
|
|
@@ -5,7 +5,7 @@ const repository_base_1 = require("./repository-base");
|
|
|
5
5
|
class SoftDeletableRepositoryBase extends repository_base_1.RepositoryBase {
|
|
6
6
|
getAll(withDeleted = false) {
|
|
7
7
|
return this.getRepository().find({
|
|
8
|
-
withDeleted
|
|
8
|
+
withDeleted,
|
|
9
9
|
});
|
|
10
10
|
}
|
|
11
11
|
getWhere(options, withDeleted = false) {
|
|
@@ -19,10 +19,10 @@ class SoftDeletableRepositoryBase extends repository_base_1.RepositoryBase {
|
|
|
19
19
|
getById(id, relations, withDeleted = false) {
|
|
20
20
|
return this.getRepository().findOne({
|
|
21
21
|
where: {
|
|
22
|
-
id
|
|
22
|
+
id,
|
|
23
23
|
},
|
|
24
24
|
relations,
|
|
25
|
-
withDeleted
|
|
25
|
+
withDeleted,
|
|
26
26
|
});
|
|
27
27
|
}
|
|
28
28
|
delete(entity, hardDelete = false) {
|
|
@@ -42,7 +42,12 @@ class SoftDeletableRepositoryBase extends repository_base_1.RepositoryBase {
|
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
44
|
deleteAll(hardDelete = false) {
|
|
45
|
-
|
|
45
|
+
if (!hardDelete) {
|
|
46
|
+
return this.getRepository().deleteAll();
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
return this.getRepository().clear();
|
|
50
|
+
}
|
|
46
51
|
}
|
|
47
52
|
}
|
|
48
53
|
exports.SoftDeletableRepositoryBase = SoftDeletableRepositoryBase;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/../src/database/repositories/soft-deletable-repository-base.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"sources":["../src/../src/database/repositories/soft-deletable-repository-base.ts"],"names":[],"mappings":";;;AAOA,uDAAmD;AAInD,MAAsB,2BAEpB,SAAQ,gCAAiB;IAChB,MAAM,CAAC,cAAuB,KAAK;QAC1C,OAAO,IAAI,CAAC,aAAa,EA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CAAC,aAAa,EAAE,CAAC,SAAS,EAAE,CAAC;QAC1C,CAAC;aAAM,CAAC;YACN,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC,KAAK,EAAE,CAAC;QACtC,CAAC;IACH,CAAC;CACF;AAhED,kEAgEC","file":"soft-deletable-repository-base.js","sourcesContent":["import {\n DeleteResult,\n FindManyOptions,\n FindOneOptions,\n FindOptionsRelations,\n FindOptionsWhere,\n} from \"typeorm\";\nimport { RepositoryBase } from \"./repository-base\";\nimport { SoftDeletable } from \"../entities\";\nimport { IdentifiableEntity } from \"../../types\";\n\nexport abstract class SoftDeletableRepositoryBase<\n T extends IdentifiableEntity & SoftDeletable\n> extends RepositoryBase<T> {\n override getAll(withDeleted: boolean = false) {\n return this.getRepository().find({\n withDeleted,\n });\n }\n\n override getWhere(options: FindManyOptions<T>, withDeleted: boolean = false) {\n options.withDeleted = withDeleted;\n return super.getWhere(options);\n }\n\n override getOneWhere(\n options: FindOneOptions<T>,\n withDeleted: boolean = false\n ) {\n options.withDeleted = withDeleted;\n return super.getOneWhere(options);\n }\n\n override getById(\n id: number,\n relations?: FindOptionsRelations<T>,\n withDeleted: boolean = false\n ) {\n return this.getRepository().findOne(<FindOneOptions<T>>{\n where: {\n id,\n },\n relations,\n withDeleted,\n });\n }\n\n override delete(entity: T, hardDelete: boolean = false) {\n if (!hardDelete) {\n return this.getRepository().softDelete(entity.id);\n } else {\n return this.getRepository().delete(entity.id);\n }\n }\n\n override deleteWhere(\n where?: FindOptionsWhere<T>,\n hardDelete: boolean = false\n ) {\n if (!hardDelete) {\n return this.getRepository().softDelete(where);\n } else {\n return this.getRepository().delete(where);\n }\n }\n\n override deleteAll(\n hardDelete: boolean = false\n ): Promise<DeleteResult> | Promise<void> {\n if (!hardDelete) {\n return this.getRepository().deleteAll();\n } else {\n return this.getRepository().clear();\n }\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "kool-koala",
|
|
3
|
-
"version": "1.7.
|
|
3
|
+
"version": "1.7.3",
|
|
4
4
|
"description": "Full-stack framework to create NodeJS applications on server side and Angular applications on the client side with ease.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
@@ -57,12 +57,11 @@
|
|
|
57
57
|
"rimraf": "^6.0.1",
|
|
58
58
|
"semantic-release": "^24.2.3",
|
|
59
59
|
"sqlite3": "^5.1.7",
|
|
60
|
-
"ts-node": "^10.9.2"
|
|
60
|
+
"ts-node": "^10.9.2",
|
|
61
|
+
"typeorm": "^0.3.25"
|
|
61
62
|
},
|
|
62
|
-
"
|
|
63
|
-
"
|
|
64
|
-
"path": "./node_modules/cz-git"
|
|
65
|
-
}
|
|
63
|
+
"peerDependencies": {
|
|
64
|
+
"typeorm": "^0.3.25"
|
|
66
65
|
},
|
|
67
66
|
"dependencies": {
|
|
68
67
|
"@types/koa": "^2.15.0",
|
|
@@ -74,7 +73,11 @@
|
|
|
74
73
|
"koa-bodyparser": "^4.4.1",
|
|
75
74
|
"koa-router": "^13.0.1",
|
|
76
75
|
"reflect-metadata": "^0.2.2",
|
|
77
|
-
"typeorm": "^0.3.22",
|
|
78
76
|
"yargs": "^17.7.2"
|
|
77
|
+
},
|
|
78
|
+
"config": {
|
|
79
|
+
"commitizen": {
|
|
80
|
+
"path": "./node_modules/cz-git"
|
|
81
|
+
}
|
|
79
82
|
}
|
|
80
83
|
}
|