kool-koala 1.3.0 → 1.4.0

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 (56) hide show
  1. package/README.md +126 -0
  2. package/common/configuration-parameters.js.map +1 -1
  3. package/common/koalapp.d.ts +6 -1
  4. package/common/koalapp.js +33 -13
  5. package/common/koalapp.js.map +1 -1
  6. package/database/entities/audited-entity-base.d.ts +6 -0
  7. package/database/entities/audited-entity-base.js +27 -0
  8. package/database/entities/audited-entity-base.js.map +1 -0
  9. package/database/entities/entity-base.d.ts +4 -0
  10. package/database/entities/entity-base.js +22 -0
  11. package/database/entities/entity-base.js.map +1 -0
  12. package/database/entities/index.d.ts +5 -0
  13. package/database/entities/index.js +23 -0
  14. package/database/entities/index.js.map +1 -0
  15. package/database/entities/interfaces/audited.d.ts +4 -0
  16. package/database/entities/interfaces/audited.js +4 -0
  17. package/database/entities/interfaces/audited.js.map +1 -0
  18. package/database/entities/interfaces/index.d.ts +2 -0
  19. package/database/entities/interfaces/index.js +20 -0
  20. package/database/entities/interfaces/index.js.map +1 -0
  21. package/database/entities/interfaces/soft-deletable.d.ts +3 -0
  22. package/database/entities/interfaces/soft-deletable.js +4 -0
  23. package/database/entities/interfaces/soft-deletable.js.map +1 -0
  24. package/database/entities/soft-deletable-audited-entity-base.d.ts +5 -0
  25. package/database/entities/soft-deletable-audited-entity-base.js +23 -0
  26. package/database/entities/soft-deletable-audited-entity-base.js.map +1 -0
  27. package/database/entities/soft-deletable-entity-base.d.ts +5 -0
  28. package/database/entities/soft-deletable-entity-base.js +23 -0
  29. package/database/entities/soft-deletable-entity-base.js.map +1 -0
  30. package/database/index.d.ts +1 -0
  31. package/database/index.js +1 -0
  32. package/database/index.js.map +1 -1
  33. package/database/repositories/index.d.ts +1 -0
  34. package/database/repositories/index.js +1 -0
  35. package/database/repositories/index.js.map +1 -1
  36. package/database/repositories/repository-base.d.ts +4 -4
  37. package/database/repositories/repository-base.js +13 -8
  38. package/database/repositories/repository-base.js.map +1 -1
  39. package/database/repositories/soft-deletable-repository-base.d.ts +13 -0
  40. package/database/repositories/soft-deletable-repository-base.js +50 -0
  41. package/database/repositories/soft-deletable-repository-base.js.map +1 -0
  42. package/middlewares/error-handler-middleware.d.ts +2 -0
  43. package/middlewares/error-handler-middleware.js +38 -0
  44. package/middlewares/error-handler-middleware.js.map +1 -0
  45. package/middlewares/transaction-middleware.d.ts +3 -0
  46. package/middlewares/transaction-middleware.js +32 -0
  47. package/middlewares/transaction-middleware.js.map +1 -0
  48. package/package.json +4 -2
  49. package/services/authorization-service.js +1 -1
  50. package/services/authorization-service.js.map +1 -1
  51. package/types/common/context.d.ts +3 -0
  52. package/types/common/context.js +4 -0
  53. package/types/common/context.js.map +1 -0
  54. package/types/common/state.d.ts +6 -0
  55. package/types/common/state.js +4 -0
  56. package/types/common/state.js.map +1 -0
package/README.md CHANGED
@@ -69,3 +69,129 @@ const configuration = new Configuration({
69
69
  ]
70
70
  });
71
71
  ```
72
+
73
+ ## Database connection
74
+
75
+ You can also setup a database connection with kool-koala, by setting a few parameters for the configuration.
76
+
77
+ ```
78
+ const configuration = new Configuration({
79
+ ...
80
+ database: {,
81
+ dataSource: new DataSource({
82
+ type: 'postgres',
83
+ host: 'localhost',
84
+ port: 5432,
85
+ username: 'username',
86
+ password: 'passwor',
87
+ database: 'database',
88
+ entities: [
89
+ // List of classes what you want to manage within the application.
90
+ ]
91
+ })
92
+ shouldRunMigrations
93
+ }
94
+ });
95
+ ```
96
+
97
+ > **Note:** For every database connection configuration what you can pass to the DataSource object, please see the documentation of [TypeORM](https://typeorm.io/data-source-options).
98
+
99
+ ## Database entities
100
+
101
+ The package provides multiple classes what you can extend to create database entities what already implement some functionalities so you don't have to implement it yourself.
102
+
103
+ > **Note:** About how you can declare the attributes of the entities, please see the documentation of [TypeORM](https://typeorm.io/entities).
104
+
105
+ ### EntityBase
106
+
107
+ This class contains an `id` attribute, which will be an auto increment id for the entities which extends this class.
108
+
109
+ ### AuditedEntityBase
110
+
111
+ Extending the `EntityBase` class, it inherits all its functionalities.
112
+
113
+ This class contains a `createdAt` attribute which will be set to the current date and time when an entity is being saved into the database.
114
+
115
+ This class also contains an `updatedAt` attribute which will be set to the current date and time when an entity is modified and saved into the database. After the entity creation it's value will be the same as the `createdAt` field's value.
116
+
117
+ ### SoftDeletableEntityBase
118
+
119
+ Extending the `EntityBase` class, it inherits all its functionalities.
120
+
121
+ This class provides the possibility to mark the entities in the database as deleted and exempt them from the query results.
122
+
123
+ It contains a `deletedAt` attribute which remains null until the entity is being deleted. After that the value of the attribute will store the date and time of deletion of the entity.
124
+
125
+ > **Note:** These functionalities only work if the entity is being manipulated with a repository which extends `SoftDeletableRepositoryBase` class.
126
+
127
+ ### SoftDeletableAuditedEntityBase
128
+
129
+ Extending the `AuditedEntityBase` class, it inherits all its functionalities.
130
+
131
+ This class combines the functionalities of the `EntityBase`, `AuditedEntityBase` and the `SoftDeletableEntityBase` classes.
132
+
133
+ ## Repositories
134
+
135
+ The package provides repository classes which help the user to manipulate entities in the database.
136
+
137
+ ### RepositoryBase
138
+
139
+ This class provides methods which implements basic manipulative and query methods for the entities.
140
+
141
+ To use this class you have to create a class which extends it and implements the abstract methods.
142
+
143
+ The class requires a generic type which have to be a class which implements the `IdentifiableEntity` interface. For example if you provide a class which extends the `EntityBase` class, that would be correct.
144
+
145
+ > **Note:** All of the methods described below mainly manipulates the entities of the type provided in the `T` generic type for the class.
146
+
147
+ > **Note:** You can find information about the following classes in the documentation of TypeORM: `FindManyOptions`, `FindOneOptions`, `FindOptionsWhere`, `FindOptionsRelations`, `DeepPartial`, `DeleteResult`
148
+
149
+ **getAll(): Promise<T[]>**
150
+
151
+ Returns a Promise which will resolve all entities from the database.
152
+
153
+ **getWhere(options: FindManyOptions<T>): Promise<T[]>**
154
+
155
+ Returns a Promise which will resolve those entities which matches the provided where criterias in the `options` parameter.
156
+
157
+ **getOneWhere(options: FindOneOptions<T>): Promise<T>**
158
+
159
+ Returns a Promise which will resolve the first entity which matches the provided where criterias in the `options` parameter.
160
+
161
+ **getById(id: number, relations?: FindOptionsRelations<T>): Promise<T>**
162
+
163
+ Returns a Promise which will resolve the entity with the provided `id`. It can also load related entities which is provided in the `relations` parameter.
164
+
165
+ **save(entity: T | DeepPartial<T>): Promise<DeepPartial<T> & T>**
166
+
167
+ Saves the provided entity into the database. If the primary key attribute is set, it will update the already existing entity, if it isn't, then it will insert the entity into the database.
168
+
169
+ Returns a Promise which will resolve the saved entity.
170
+
171
+ **delete(entity: T): Promise<DeleteResult>**
172
+
173
+ Deletes the specified entity from the database.
174
+
175
+ Returns a Promise which will resolve an object which contain information about the deletion.
176
+
177
+ **deleteWhere(where?: FindOptionsWhere<T>): Promise<DeleteResult>**
178
+
179
+ Deletes those entities which matches the provided where criterias.
180
+
181
+ Returns a Promise which will resolve an object which contain information about the deletion.
182
+
183
+ **deleteAll(): Promise<DeleteResult>**
184
+
185
+ Deletes all entities from the database.
186
+
187
+ Returns a Promise which will resolve an object which contain information about the deletion.
188
+
189
+ ### SoftDeletableRepositoryBase
190
+
191
+ This class extends the `RepositoryBase` class.
192
+
193
+ The class requires a generic type which have to be a class which implements the `IdentifiableEntity` and the `SoftDeletable` interfaces. For example if you provide a class which extends the `SoftDeletableEntityBase` class or the `SoftDeletableAuditedEntityBase`, that would be correct.
194
+
195
+ The `getAll`, `getWhere`, `getOneWhere` and the `getById` methods works the same way as in the `RepositoryBase` class they just have an optional `boolean` typed `withDeleted` parameter at the end of the parameters list, which is `false` by default and it handles if the entities which is marked as deleted have to be returned by the query or not. If it is true, it will returns the entities which is marked as deleted.
196
+
197
+ The `delete`, `deleteWhere` and the `deleteAll` methods works the same way as in the `RepositoryBase` class they just have an optional `boolean` typed `hardDelete` parameter at the end of the parameters list, which is `false` by default and if it is true, it will not only marks the entities as deleted but literally delete them from the database.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/../src/common/configuration-parameters.ts"],"names":[],"mappings":"","file":"configuration-parameters.js","sourcesContent":["import { ControllerConstructor } from \"../controllers\";\nimport { AuthenticableEntity } from \"../types\";\nimport { StringEnum } from \"../types/common/string-enum\";\nimport { JwtConfigurationParameters } from \"./jwt-configuration-parameters\";\nimport { DatabaseConfigurationParamters } from \"./database-configuration-paramters\";\nimport { RepositoryBase } from \"../database\";\n\nexport interface ConfigurationParameters<\n U extends AuthenticableEntity = AuthenticableEntity,\n P extends StringEnum = {}\n> {\n port: number,\n controllers?: (ControllerConstructor)[],\n database?: DatabaseConfigurationParamters,\n jwt?: JwtConfigurationParameters,\n userRepository?: RepositoryBase<U>,\n permissionType?: P,\n restPrefix?: string,\n}"]}
1
+ {"version":3,"sources":["../src/../src/common/configuration-parameters.ts"],"names":[],"mappings":"","file":"configuration-parameters.js","sourcesContent":["import { ControllerConstructor } from \"../controllers\";\nimport { AuthenticableEntity } from \"../types\";\nimport { StringEnum } from \"../types/common/string-enum\";\nimport { JwtConfigurationParameters } from \"./jwt-configuration-parameters\";\nimport { DatabaseConfigurationParamters } from \"./database-configuration-paramters\";\nimport { RepositoryBase } from \"../database\";\n\nexport interface ConfigurationParameters<\n U extends AuthenticableEntity = AuthenticableEntity,\n P extends StringEnum = {}\n> {\n port: number,\n controllers?: (ControllerConstructor)[],\n database?: DatabaseConfigurationParamters,\n jwt?: JwtConfigurationParameters,\n userRepository?: RepositoryBase<U>,\n permissionType?: P,\n restPrefix?: string,\n}\n"]}
@@ -11,17 +11,22 @@ export declare class KoalApp<U extends AuthenticableEntity, P extends StringEnum
11
11
  private koa;
12
12
  private routerService;
13
13
  private databaseConnection;
14
+ private server;
14
15
  private authorizationService;
15
16
  private constructor();
16
17
  static getInstance<T extends AuthenticableEntity, Q extends StringEnum>(configuration?: Configuration<T, Q>): KoalApp<T, Q>;
17
- static resetInstance(): void;
18
+ static resetInstance(): Promise<void>;
18
19
  getConfiguration(): Configuration<U, P>;
19
20
  getRouterService(): RouterService;
20
21
  getDatabaseConnection(): DataSource;
21
22
  initialize(): Promise<void>;
23
+ setupDatabaseConnection(): Promise<void>;
24
+ setupErrorHandler(): void;
25
+ setupTransaction(): void;
22
26
  registerStaticFileServerMiddleware(): void;
23
27
  registerEndpoints(): void;
24
28
  start(callback?: (configuration: Configuration<U, P>) => void): Promise<void>;
29
+ stop(): void;
25
30
  authorizationHeaderParser(context: ParameterizedContext, next: Next): Promise<void>;
26
31
  errorHandler(context: ParameterizedContext, next: Next): Promise<void>;
27
32
  getAuthorizationService(): AuthorizationService<U, P>;
package/common/koalapp.js CHANGED
@@ -22,6 +22,8 @@ const types_1 = require("../types");
22
22
  const koa_static_1 = __importDefault(require("koa-static"));
23
23
  const path_1 = __importDefault(require("path"));
24
24
  const fs_1 = __importDefault(require("fs"));
25
+ const error_handler_middleware_1 = require("../middlewares/error-handler-middleware");
26
+ const transaction_middleware_1 = require("../middlewares/transaction-middleware");
25
27
  class KoalApp {
26
28
  constructor(configuration) {
27
29
  this.configuration = configuration;
@@ -37,7 +39,10 @@ class KoalApp {
37
39
  return KoalApp.instance;
38
40
  }
39
41
  static resetInstance() {
40
- KoalApp.instance = undefined;
42
+ return __awaiter(this, void 0, void 0, function* () {
43
+ yield KoalApp.getInstance().getDatabaseConnection().destroy();
44
+ KoalApp.instance = undefined;
45
+ });
41
46
  }
42
47
  getConfiguration() {
43
48
  return this.configuration;
@@ -51,21 +56,16 @@ class KoalApp {
51
56
  initialize() {
52
57
  return __awaiter(this, void 0, void 0, function* () {
53
58
  try {
54
- if (this.configuration.getDatabase()) {
55
- this.databaseConnection = yield this.configuration.getDatabase().dataSource.initialize();
56
- if (this.configuration.getDatabase().shouldRunMigrations) {
57
- console.log("Executing database migrations...");
58
- yield this.databaseConnection.runMigrations();
59
- console.log("Database migrations executed.");
60
- }
61
- console.log("Database connection initialized.");
62
- }
59
+ yield this.setupDatabaseConnection();
60
+ console.log("Database connection initialized.");
61
+ this.setupErrorHandler();
62
+ console.log("Error handler initialized.");
63
+ this.setupTransaction();
64
+ console.log("Transaction starter middleware initialized.");
63
65
  this.koa.use(this.authorizationHeaderParser.bind(this));
64
66
  console.log("Authorization header parser initialized.");
65
67
  this.koa.use((0, koa_bodyparser_1.default)());
66
68
  console.log("Body parser initialized.");
67
- this.koa.use(this.errorHandler.bind(this));
68
- console.log("Error handler initialized.");
69
69
  this.registerStaticFileServerMiddleware();
70
70
  console.log("Static file server initialized.");
71
71
  this.registerEndpoints();
@@ -77,6 +77,20 @@ class KoalApp {
77
77
  }
78
78
  });
79
79
  }
80
+ setupDatabaseConnection() {
81
+ return __awaiter(this, void 0, void 0, function* () {
82
+ if (this.configuration.getDatabase()) {
83
+ this.databaseConnection = yield this.configuration.getDatabase().dataSource.initialize();
84
+ yield this.databaseConnection.runMigrations();
85
+ }
86
+ });
87
+ }
88
+ setupErrorHandler() {
89
+ this.koa.use(error_handler_middleware_1.errorHandlerMiddleware);
90
+ }
91
+ setupTransaction() {
92
+ this.koa.use(transaction_middleware_1.transactionMiddleware);
93
+ }
80
94
  registerStaticFileServerMiddleware() {
81
95
  this.koa.use((0, koa_static_1.default)(path_1.default.join(__dirname, '../client', 'browser')));
82
96
  this.koa.use((0, koa_static_1.default)(path_1.default.join(__dirname, '../../static')));
@@ -99,13 +113,19 @@ class KoalApp {
99
113
  }
100
114
  start(callback) {
101
115
  return __awaiter(this, void 0, void 0, function* () {
102
- this.koa.listen(this.configuration.getPort(), () => {
116
+ this.server = this.koa.listen(this.configuration.getPort(), () => {
103
117
  if (callback) {
104
118
  callback(this.configuration);
105
119
  }
106
120
  });
107
121
  });
108
122
  }
123
+ stop() {
124
+ if (this.server) {
125
+ this.server.close();
126
+ this.server = undefined;
127
+ }
128
+ }
109
129
  authorizationHeaderParser(context, next) {
110
130
  return __awaiter(this, void 0, void 0, function* () {
111
131
  const authHeader = context.headers.authorization;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/../src/common/koalapp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,8CAAsD;AAEtD,+DAA2D;AAG3D,+CAA2C;AAC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ameterizedContext } 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 serve from \"koa-static\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { AuthorizationService } from '../services';\nimport { StringEnum } from '../types/common/string-enum';\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 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 resetInstance() {\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\n async initialize() {\n try {\n if (this.configuration.getDatabase()) {\n this.databaseConnection = await this.configuration.getDatabase().dataSource.initialize();\n if (this.configuration.getDatabase().shouldRunMigrations) {\n console.log(\"Executing database migrations...\");\n await this.databaseConnection.runMigrations();\n console.log(\"Database migrations executed.\");\n }\n console.log(\"Database connection initialized.\");\n }\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.koa.use(this.errorHandler.bind(this));\n console.log(\"Error handler initialized.\");\n this.registerStaticFileServerMiddleware();\n console.log(\"Static file server initialized.\");\n this.registerEndpoints();\n console.log(\"Endpoints registered.\");\n } catch (error) {\n console.log(\"Error during database initialization...\", error);\n throw new Error('Error during application intialization...');\n }\n }\n\n registerStaticFileServerMiddleware() {\n this.koa.use(serve(path.join(__dirname, '../client', 'browser')));\n this.koa.use(serve(path.join(__dirname, '../../static')));\n this.koa.use(async (ctx, next) => {\n const requestPath = ctx.request.path;\n\n if (!requestPath.startsWith(this.configuration.getRestPrefix()) && !/\\.[a-z]+$/.test(requestPath)) {\n ctx.type = 'html';\n ctx.body = fs.createReadStream(path.join(__dirname, '../client', 'browser', 'index.html'));\n } else {\n await next();\n }\n });\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 async start(callback?: (configuration: Configuration<U, P>) => void) {\n this.koa.listen(this.configuration.getPort(), () => {\n if (callback) {\n callback(this.configuration);\n }\n });\n }\n\n async authorizationHeaderParser(context: ParameterizedContext, next: Next) {\n const authHeader = context.headers.authorization;\n if (authHeader) {\n const token = authHeader.split(' ')[1];\n try {\n context.state.user = 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: ParameterizedContext, 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,8CAAsD;AAEtD,+DAA2D;AAG3D,+CAA2C;AAC3C,gEAA+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AAO;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;AAnKD,0BAmKC","file":"koalapp.js","sourcesContent":["import Koa, { Next, ParameterizedContext } 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 serve from \"koa-static\";\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';\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.registerStaticFileServerMiddleware();\n console.log(\"Static file server initialized.\");\n this.registerEndpoints();\n console.log(\"Endpoints registered.\");\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 registerStaticFileServerMiddleware() {\n this.koa.use(serve(path.join(__dirname, '../client', 'browser')));\n this.koa.use(serve(path.join(__dirname, '../../static')));\n this.koa.use(async (ctx, next) => {\n const requestPath = ctx.request.path;\n\n if (!requestPath.startsWith(this.configuration.getRestPrefix()) && !/\\.[a-z]+$/.test(requestPath)) {\n ctx.type = 'html';\n ctx.body = fs.createReadStream(path.join(__dirname, '../client', 'browser', 'index.html'));\n } else {\n await next();\n }\n });\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 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 if (this.server) {\n this.server.close();\n this.server = undefined;\n }\n }\n\n async authorizationHeaderParser(context: ParameterizedContext, next: Next) {\n const authHeader = context.headers.authorization;\n if (authHeader) {\n const token = authHeader.split(' ')[1];\n try {\n context.state.user = 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: ParameterizedContext, 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}"]}
@@ -0,0 +1,6 @@
1
+ import { EntityBase } from "./entity-base";
2
+ import { Audited } from "./interfaces/audited";
3
+ export declare abstract class AuditedEntityBase extends EntityBase implements Audited {
4
+ createdAt: Date;
5
+ updatedAt: Date;
6
+ }
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.AuditedEntityBase = void 0;
13
+ const typeorm_1 = require("typeorm");
14
+ const entity_base_1 = require("./entity-base");
15
+ class AuditedEntityBase extends entity_base_1.EntityBase {
16
+ }
17
+ exports.AuditedEntityBase = AuditedEntityBase;
18
+ __decorate([
19
+ (0, typeorm_1.CreateDateColumn)(),
20
+ __metadata("design:type", Date)
21
+ ], AuditedEntityBase.prototype, "createdAt", void 0);
22
+ __decorate([
23
+ (0, typeorm_1.UpdateDateColumn)(),
24
+ __metadata("design:type", Date)
25
+ ], AuditedEntityBase.prototype, "updatedAt", void 0);
26
+
27
+ //# sourceMappingURL=audited-entity-base.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/../src/database/entities/audited-entity-base.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,qCAA6D;AAC7D,+CAA2C;AAG3C,MAAsB,iBAAkB,SAAQ,wBAAU;CAMzD;AAND,8CAMC;AAJC;IADC,IAAA,0BAAgB,GAAE;8BACR,IAAI;oDAAC;AAGhB;IADC,IAAA,0BAAgB,GAAE;8BACR,IAAI;oDAAC","file":"audited-entity-base.js","sourcesContent":["import { CreateDateColumn, UpdateDateColumn } from \"typeorm\";\nimport { EntityBase } from \"./entity-base\";\nimport { Audited } from \"./interfaces/audited\";\n\nexport abstract class AuditedEntityBase extends EntityBase implements Audited {\n @CreateDateColumn()\n createdAt: Date;\n\n @UpdateDateColumn()\n updatedAt: Date;\n}"]}
@@ -0,0 +1,4 @@
1
+ import { IdentifiableEntity } from "../../types";
2
+ export declare abstract class EntityBase implements IdentifiableEntity {
3
+ id: number;
4
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.EntityBase = void 0;
13
+ const typeorm_1 = require("typeorm");
14
+ class EntityBase {
15
+ }
16
+ exports.EntityBase = EntityBase;
17
+ __decorate([
18
+ (0, typeorm_1.PrimaryGeneratedColumn)(),
19
+ __metadata("design:type", Number)
20
+ ], EntityBase.prototype, "id", void 0);
21
+
22
+ //# sourceMappingURL=entity-base.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/../src/database/entities/entity-base.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,qCAAiD;AAGjD,MAAsB,UAAU;CAG/B;AAHD,gCAGC;AADC;IADC,IAAA,gCAAsB,GAAE;;sCACd","file":"entity-base.js","sourcesContent":["import { PrimaryGeneratedColumn } from \"typeorm\";\nimport { IdentifiableEntity } from \"../../types\";\n\nexport abstract class EntityBase implements IdentifiableEntity {\n @PrimaryGeneratedColumn()\n id: number;\n}\n"]}
@@ -0,0 +1,5 @@
1
+ export * from './interfaces';
2
+ export * from './audited-entity-base';
3
+ export * from './soft-deletable-audited-entity-base';
4
+ export * from './entity-base';
5
+ export * from './soft-deletable-entity-base';
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./interfaces"), exports);
18
+ __exportStar(require("./audited-entity-base"), exports);
19
+ __exportStar(require("./soft-deletable-audited-entity-base"), exports);
20
+ __exportStar(require("./entity-base"), exports);
21
+ __exportStar(require("./soft-deletable-entity-base"), exports);
22
+
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/../src/database/entities/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,+CAA6B;AAC7B,wDAAsC;AACtC,uEAAqD;AACrD,gDAA8B;AAC9B,+DAA6C","file":"index.js","sourcesContent":["export * from './interfaces';\nexport * from './audited-entity-base';\nexport * from './soft-deletable-audited-entity-base';\nexport * from './entity-base';\nexport * from './soft-deletable-entity-base';\n"]}
@@ -0,0 +1,4 @@
1
+ export interface Audited {
2
+ createdAt: Date;
3
+ updatedAt: Date;
4
+ }
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+
4
+ //# sourceMappingURL=audited.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/../src/database/entities/interfaces/audited.ts"],"names":[],"mappings":"","file":"audited.js","sourcesContent":["export interface Audited {\n createdAt: Date;\n updatedAt: Date;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export * from './audited';
2
+ export * from './soft-deletable';
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./audited"), exports);
18
+ __exportStar(require("./soft-deletable"), exports);
19
+
20
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/../src/database/entities/interfaces/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,mDAAiC","file":"index.js","sourcesContent":["export * from './audited';\nexport * from './soft-deletable';\n"]}
@@ -0,0 +1,3 @@
1
+ export interface SoftDeletable {
2
+ deletedAt: Date;
3
+ }
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+
4
+ //# sourceMappingURL=soft-deletable.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/../src/database/entities/interfaces/soft-deletable.ts"],"names":[],"mappings":"","file":"soft-deletable.js","sourcesContent":["export interface SoftDeletable {\n deletedAt: Date;\n}\n"]}
@@ -0,0 +1,5 @@
1
+ import { SoftDeletable } from "./interfaces/soft-deletable";
2
+ import { AuditedEntityBase } from "./audited-entity-base";
3
+ export declare abstract class SoftDeletableAuditedEntityBase extends AuditedEntityBase implements SoftDeletable {
4
+ deletedAt: Date;
5
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.SoftDeletableAuditedEntityBase = void 0;
13
+ const typeorm_1 = require("typeorm");
14
+ const audited_entity_base_1 = require("./audited-entity-base");
15
+ class SoftDeletableAuditedEntityBase extends audited_entity_base_1.AuditedEntityBase {
16
+ }
17
+ exports.SoftDeletableAuditedEntityBase = SoftDeletableAuditedEntityBase;
18
+ __decorate([
19
+ (0, typeorm_1.DeleteDateColumn)(),
20
+ __metadata("design:type", Date)
21
+ ], SoftDeletableAuditedEntityBase.prototype, "deletedAt", void 0);
22
+
23
+ //# sourceMappingURL=soft-deletable-audited-entity-base.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/../src/database/entities/soft-deletable-audited-entity-base.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,qCAA2C;AAE3C,+DAA0D;AAE1D,MAAsB,8BAA+B,SAAQ,uCAAiB;CAG7E;AAHD,wEAGC;AADC;IADC,IAAA,0BAAgB,GAAE;8BACR,IAAI;iEAAC","file":"soft-deletable-audited-entity-base.js","sourcesContent":["import { DeleteDateColumn } from \"typeorm\";\nimport { SoftDeletable } from \"./interfaces/soft-deletable\";\nimport { AuditedEntityBase } from \"./audited-entity-base\";\n\nexport abstract class SoftDeletableAuditedEntityBase extends AuditedEntityBase implements SoftDeletable {\n @DeleteDateColumn()\n deletedAt: Date;\n}\n"]}
@@ -0,0 +1,5 @@
1
+ import { EntityBase } from "./entity-base";
2
+ import { SoftDeletable } from "./interfaces/soft-deletable";
3
+ export declare abstract class SoftDeletableEntityBase extends EntityBase implements SoftDeletable {
4
+ deletedAt: Date;
5
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.SoftDeletableEntityBase = void 0;
13
+ const typeorm_1 = require("typeorm");
14
+ const entity_base_1 = require("./entity-base");
15
+ class SoftDeletableEntityBase extends entity_base_1.EntityBase {
16
+ }
17
+ exports.SoftDeletableEntityBase = SoftDeletableEntityBase;
18
+ __decorate([
19
+ (0, typeorm_1.DeleteDateColumn)(),
20
+ __metadata("design:type", Date)
21
+ ], SoftDeletableEntityBase.prototype, "deletedAt", void 0);
22
+
23
+ //# sourceMappingURL=soft-deletable-entity-base.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/../src/database/entities/soft-deletable-entity-base.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,qCAAmD;AACnD,+CAA2C;AAG3C,MAAsB,uBAAwB,SAAQ,wBAAU;CAG/D;AAHD,0DAGC;AADC;IADC,IAAA,0BAAgB,GAAE;8BACR,IAAI;0DAAC","file":"soft-deletable-entity-base.js","sourcesContent":["import { Column, DeleteDateColumn } from \"typeorm\";\nimport { EntityBase } from \"./entity-base\";\nimport { SoftDeletable } from \"./interfaces/soft-deletable\";\n\nexport abstract class SoftDeletableEntityBase extends EntityBase implements SoftDeletable {\n @DeleteDateColumn()\n deletedAt: Date;\n}\n"]}
@@ -1 +1,2 @@
1
+ export * from './entities';
1
2
  export * from './repositories';
package/database/index.js CHANGED
@@ -14,6 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./entities"), exports);
17
18
  __exportStar(require("./repositories"), exports);
18
19
 
19
20
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/../src/database/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,iDAA+B","file":"index.js","sourcesContent":["export * from './repositories';\n"]}
1
+ {"version":3,"sources":["../src/../src/database/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,6CAA2B;AAC3B,iDAA+B","file":"index.js","sourcesContent":["export * from './entities';\nexport * from './repositories';\n"]}
@@ -1 +1,2 @@
1
1
  export * from './repository-base';
2
+ export * from './soft-deletable-repository-base';
@@ -15,5 +15,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./repository-base"), exports);
18
+ __exportStar(require("./soft-deletable-repository-base"), exports);
18
19
 
19
20
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/../src/database/repositories/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,oDAAkC","file":"index.js","sourcesContent":["export * from './repository-base';\n"]}
1
+ {"version":3,"sources":["../src/../src/database/repositories/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,oDAAkC;AAClC,mEAAiD","file":"index.js","sourcesContent":["export * from './repository-base';\nexport * from './soft-deletable-repository-base';\n"]}
@@ -1,8 +1,8 @@
1
- import { DataSource, DeepPartial, FindManyOptions, FindOneOptions, FindOptionsRelations, Repository } from "typeorm";
1
+ import { DeepPartial, 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;
5
- constructor(databaseConnection?: DataSource);
5
+ constructor(queryRunner?: QueryRunner);
6
6
  getRepository(): Repository<T>;
7
7
  abstract getEntityType(): new () => T;
8
8
  getAll(): Promise<T[]>;
@@ -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
- find(where: FindManyOptions<T>): Promise<T[]>;
14
- findOne(where: FindOneOptions<T>): Promise<T>;
15
13
  delete(entity: T): Promise<import("typeorm").DeleteResult>;
14
+ deleteWhere(where?: FindOptionsWhere<T>): Promise<import("typeorm").DeleteResult>;
15
+ deleteAll(): Promise<import("typeorm").DeleteResult>;
16
16
  }
@@ -3,8 +3,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RepositoryBase = void 0;
4
4
  const common_1 = require("../../common");
5
5
  class RepositoryBase {
6
- constructor(databaseConnection) {
7
- this._repository = (databaseConnection !== null && databaseConnection !== void 0 ? databaseConnection : common_1.KoalApp.getInstance().getDatabaseConnection()).getRepository(this.getEntityType());
6
+ constructor(queryRunner) {
7
+ if (queryRunner === undefined) {
8
+ this._repository = common_1.KoalApp.getInstance().getDatabaseConnection().getRepository(this.getEntityType());
9
+ }
10
+ else {
11
+ this._repository = queryRunner.manager.getRepository(this.getEntityType());
12
+ }
8
13
  }
9
14
  getRepository() {
10
15
  return this._repository;
@@ -29,15 +34,15 @@ class RepositoryBase {
29
34
  save(entity) {
30
35
  return this.getRepository().save(entity);
31
36
  }
32
- find(where) {
33
- return this.getRepository().find(where);
34
- }
35
- findOne(where) {
36
- return this.getRepository().findOne(where);
37
- }
38
37
  delete(entity) {
39
38
  return this.getRepository().delete(entity.id);
40
39
  }
40
+ deleteWhere(where) {
41
+ return this.getRepository().delete(where);
42
+ }
43
+ deleteAll() {
44
+ return this.deleteWhere({});
45
+ }
41
46
  }
42
47
  exports.RepositoryBase = RepositoryBase;
43
48
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/../src/database/repositories/repository-base.ts"],"names":[],"mappings":";;;AAEA,yCAAuC;AAEvC,MAAsB,cAAc;IAElC,YAAY,kBAA+B;QACzC,IAAI,CAAC,WAAW,GAAG,CAAC,kBAAkB,aAAlB,kBAAkB,cAAlB,kBAAkB,GAAI,gBAAO,CAAC,WAAW,EAAE,CAAC,qBAAqB,EAAE,CAAC,CAAC,aAAa,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC,CAAC;IAC/H,CAAC;IACD,aAAa;QACX,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;IAED,MAAM;QACJ,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC;IACjC,CAAC;IACD,QAAQ,CAAC,OAA2B;QAClC,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACxC,CAAC;IACD,WAAW,CAAC,OAA0B;QACpC,OAAO,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAC3C,CAAC;IACD,OAAO,CAAC,EAAU,EAAE,SAAmC;QACrD,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC,OAAO,CAAoB;YACrD,KAAK,EAAE;gBACL,EAAE;aACH;YACD,SAAS;SACV,CAAC,CAAC;IACL,CAAC;IACD,IAAI,CAAC,MAA0B;QAC7B,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC3C,CAAC;IACD,IAAI,CAAC,KAAyB;QAC5B,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;IACD,OAAO,CAAC,KAAwB;QAC9B,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IAC7C,CAAC;IACD,MAAM,CAAC,MAAS;QACd,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IAChD,CAAC;CACF;AAtCD,wCAsCC","file":"repository-base.js","sourcesContent":["import { DataSource, DeepPartial, FindManyOptions, FindOneOptions, FindOptionsRelations, Repository } 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(databaseConnection?: DataSource) {\n this._repository = (databaseConnection ?? KoalApp.getInstance().getDatabaseConnection()).getRepository(this.getEntityType());\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 find(where: FindManyOptions<T>) {\n return this.getRepository().find(where);\n }\n findOne(where: FindOneOptions<T>) {\n return this.getRepository().findOne(where);\n }\n delete(entity: T) {\n return this.getRepository().delete(entity.id);\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/../src/database/repositories/repository-base.ts"],"names":[],"mappings":";;;AAEA,yCAAuC;AAEvC,MAAsB,cAAc;IAElC,YAAY,WAAyB;QACnC,IAAI,WAAW,KAAK,SAAS,EAAE,CAAC;YAC9B,IAAI,CAAC,WAAW,GAAG,gBAAO,CAAC,WAAW,EAAE,CAAC,qBAAqB,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC,CAAC;QACvG,CAAC;aACI,CAAC;YACJ,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC,CAAC;QAC7E,CAAC;IACH,CAAC;IACD,aAAa;QACX,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;IAED,MAAM;QACJ,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC;IACjC,CAAC;IACD,QAAQ,CAAC,OAA2B;QAClC,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACxC,CAAC;IACD,WAAW,CAAC,OAA0B;QACpC,OAAO,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAC3C,CAAC;IACD,OAAO,CAAC,EAAU,EAAE,SAAmC;QACrD,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC,OAAO,CAAoB;YACrD,KAAK,EAAE;gBACL,EAAE;aACH;YACD,SAAS;SACV,CAAC,CAAC;IACL,CAAC;IACD,IAAI,CAAC,MAA0B;QAC7B,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC3C,CAAC;IACD,MAAM,CAAC,MAAS;QACd,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IAChD,CAAC;IACD,WAAW,CAAC,KAA2B;QACrC,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC5C,CAAC;IACD,SAAS;QACP,OAAO,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;IAC9B,CAAC;CACF;AA3CD,wCA2CC","file":"repository-base.js","sourcesContent":["import { DeepPartial, FindManyOptions, FindOneOptions, FindOptionsRelations, FindOptionsWhere, QueryRunner, Repository } 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().getDatabaseConnection().getRepository(this.getEntityType());\n }\n else {\n this._repository = queryRunner.manager.getRepository(this.getEntityType());\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() {\n return this.deleteWhere({});\n }\n}\n"]}
@@ -0,0 +1,13 @@
1
+ import { DeleteResult, FindManyOptions, FindOneOptions, FindOptionsRelations, FindOptionsWhere } from "typeorm";
2
+ import { RepositoryBase } from "./repository-base";
3
+ import { SoftDeletable } from "../entities";
4
+ import { IdentifiableEntity } from "../../types";
5
+ export declare abstract class SoftDeletableRepositoryBase<T extends IdentifiableEntity & SoftDeletable> extends RepositoryBase<T> {
6
+ getAll(withDeleted?: boolean): Promise<T[]>;
7
+ getWhere(options: FindManyOptions<T>, withDeleted?: boolean): Promise<T[]>;
8
+ getOneWhere(options: FindOneOptions<T>, withDeleted?: boolean): Promise<T>;
9
+ getById(id: number, relations?: FindOptionsRelations<T>, withDeleted?: boolean): Promise<T>;
10
+ delete(entity: T, hardDelete?: boolean): Promise<DeleteResult>;
11
+ deleteWhere(where?: FindOptionsWhere<T>, hardDelete?: boolean): Promise<DeleteResult>;
12
+ deleteAll(hardDelete?: boolean): Promise<DeleteResult>;
13
+ }
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SoftDeletableRepositoryBase = void 0;
4
+ const repository_base_1 = require("./repository-base");
5
+ class SoftDeletableRepositoryBase extends repository_base_1.RepositoryBase {
6
+ getAll(withDeleted = false) {
7
+ return this.getRepository().find({
8
+ withDeleted
9
+ });
10
+ }
11
+ getWhere(options, withDeleted = false) {
12
+ options.withDeleted = withDeleted;
13
+ return super.getWhere(options);
14
+ }
15
+ getOneWhere(options, withDeleted = false) {
16
+ options.withDeleted = withDeleted;
17
+ return super.getOneWhere(options);
18
+ }
19
+ getById(id, relations, withDeleted = false) {
20
+ return this.getRepository().findOne({
21
+ where: {
22
+ id
23
+ },
24
+ relations,
25
+ withDeleted
26
+ });
27
+ }
28
+ delete(entity, hardDelete = false) {
29
+ if (!hardDelete) {
30
+ return this.getRepository().softDelete(entity.id);
31
+ }
32
+ else {
33
+ return this.getRepository().delete(entity.id);
34
+ }
35
+ }
36
+ deleteWhere(where, hardDelete = false) {
37
+ if (!hardDelete) {
38
+ return this.getRepository().softDelete(where);
39
+ }
40
+ else {
41
+ return this.getRepository().delete(where);
42
+ }
43
+ }
44
+ deleteAll(hardDelete = false) {
45
+ return this.deleteWhere({}, hardDelete);
46
+ }
47
+ }
48
+ exports.SoftDeletableRepositoryBase = SoftDeletableRepositoryBase;
49
+
50
+ //# sourceMappingURL=soft-deletable-repository-base.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/../src/database/repositories/soft-deletable-repository-base.ts"],"names":[],"mappings":";;;AACA,uDAAmD;AAInD,MAAsB,2BAA0E,SAAQ,gCAAiB;IAC9G,MAAM,CAAC,cAAuB,KAAK;QAC1C,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC,IAAI,CAAC;YAC/B,WAAW;SACZ,CAAC,CAAC;IACL,CAAC;IAEQ,QAAQ,CAAC,OAA2B,EAAE,cAAuB,KAAK;Q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sRelations, FindOptionsWhere } from \"typeorm\";\nimport { RepositoryBase } from \"./repository-base\";\nimport { SoftDeletable } from \"../entities\";\nimport { IdentifiableEntity } from \"../../types\";\n\nexport abstract class SoftDeletableRepositoryBase<T extends IdentifiableEntity & SoftDeletable> 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(options: FindOneOptions<T>, withDeleted: boolean = false) {\n options.withDeleted = withDeleted;\n return super.getOneWhere(options);\n }\n\n override getById(id: number, relations?: FindOptionsRelations<T>, withDeleted: boolean = false) {\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 }\n else {\n return this.getRepository().delete(entity.id);\n }\n }\n\n override deleteWhere(where?: FindOptionsWhere<T>, hardDelete: boolean = false) {\n if (!hardDelete) {\n return this.getRepository().softDelete(where);\n }\n else {\n return this.getRepository().delete(where);\n }\n }\n\n override deleteAll(hardDelete: boolean = false): Promise<DeleteResult> {\n return this.deleteWhere({}, hardDelete);\n }\n}"]}
@@ -0,0 +1,2 @@
1
+ import { Context } from "../types/common/context";
2
+ export declare const errorHandlerMiddleware: (context: Context, next: () => Promise<any>) => Promise<void>;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.errorHandlerMiddleware = void 0;
13
+ const common_1 = require("../common");
14
+ const types_1 = require("../types");
15
+ const errorHandlerMiddleware = (context, next) => __awaiter(void 0, void 0, void 0, function* () {
16
+ try {
17
+ yield next();
18
+ }
19
+ catch (error) {
20
+ console.log(error);
21
+ if (error instanceof types_1.ErrorBase) {
22
+ context.status = error.getStatusCode();
23
+ context.body = {
24
+ success: false,
25
+ message: error.message
26
+ };
27
+ }
28
+ else {
29
+ context.status = common_1.StatusCode.INTERNAL_SERVER_ERROR;
30
+ context.body = {
31
+ success: false
32
+ };
33
+ }
34
+ }
35
+ });
36
+ exports.errorHandlerMiddleware = errorHandlerMiddleware;
37
+
38
+ //# sourceMappingURL=error-handler-middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/../src/middlewares/error-handler-middleware.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,sCAAuC;AACvC,oCAAmD;AAG5C,MAAM,sBAAsB,GAAG,CAAO,OAAgB,EAAE,IAAwB,EAAE,EAAE;IACzF,IAAI,CAAC;QACH,MAAM,IAAI,EAAE,CAAC;IACf,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACnB,IAAI,KAAK,YAAY,iBAAS,EAAE,CAAC;YAC/B,OAAO,CAAC,MAAM,GAAG,KAAK,CAAC,aAAa,EAAE,CAAC;YACvC,OAAO,CAAC,IAAI,GAAiB;gBAC3B,OAAO,EAAE,KAAK;gBACd,OAAO,EAAE,KAAK,CAAC,OAAO;aACvB,CAAC;QACJ,CAAC;aACI,CAAC;YACJ,OAAO,CAAC,MAAM,GAAG,mBAAU,CAAC,qBAAqB,CAAC;YAClD,OAAO,CAAC,IAAI,GAAiB;gBAC3B,OAAO,EAAE,KAAK;aACf,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC,CAAA,CAAA;AAnBY,QAAA,sBAAsB,0BAmBlC","file":"error-handler-middleware.js","sourcesContent":["import { StatusCode } from \"../common\";\nimport { BaseResponse, ErrorBase } from \"../types\";\nimport { Context } from \"../types/common/context\";\n\nexport const errorHandlerMiddleware = async (context: Context, next: () => Promise<any>) => {\n try {\n await next();\n } catch (error) {\n console.log(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 context.status = StatusCode.INTERNAL_SERVER_ERROR;\n context.body = <BaseResponse>{\n success: false\n };\n }\n }\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import { Middleware } from "koa";
2
+ import { State } from "../types/common/state";
3
+ export declare const transactionMiddleware: Middleware<State>;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.transactionMiddleware = void 0;
13
+ const common_1 = require("../common");
14
+ const transactionMiddleware = (context, next) => __awaiter(void 0, void 0, void 0, function* () {
15
+ const queryRunner = common_1.KoalApp.getInstance().getDatabaseConnection().createQueryRunner();
16
+ context.state.queryRunner = queryRunner;
17
+ queryRunner.startTransaction();
18
+ try {
19
+ yield next();
20
+ yield queryRunner.commitTransaction();
21
+ }
22
+ catch (error) {
23
+ yield queryRunner.rollbackTransaction();
24
+ throw error;
25
+ }
26
+ finally {
27
+ yield queryRunner.release();
28
+ }
29
+ });
30
+ exports.transactionMiddleware = transactionMiddleware;
31
+
32
+ //# sourceMappingURL=transaction-middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/../src/middlewares/transaction-middleware.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,sCAAoC;AAE7B,MAAM,qBAAqB,GAAsB,CAAO,OAAO,EAAE,IAAI,EAAE,EAAE;IAC9E,MAAM,WAAW,GAAG,gBAAO,CAAC,WAAW,EAAE,CAAC,qBAAqB,EAAE,CAAC,iBAAiB,EAAE,CAAC;IACtF,OAAO,CAAC,KAAK,CAAC,WAAW,GAAG,WAAW,CAAC;IACxC,WAAW,CAAC,gBAAgB,EAAE,CAAC;IAC/B,IAAI,CAAC;QACH,MAAM,IAAI,EAAE,CAAC;QACb,MAAM,WAAW,CAAC,iBAAiB,EAAE,CAAC;IACxC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,WAAW,CAAC,mBAAmB,EAAE,CAAC;QACxC,MAAM,KAAK,CAAC;IACd,CAAC;YAAS,CAAC;QACT,MAAM,WAAW,CAAC,OAAO,EAAE,CAAC;IAC9B,CAAC;AACH,CAAC,CAAA,CAAC;AAbW,QAAA,qBAAqB,yBAahC","file":"transaction-middleware.js","sourcesContent":["import { Middleware } from \"koa\";\nimport { State } from \"../types/common/state\";\nimport { KoalApp } from \"../common\";\n\nexport const transactionMiddleware: Middleware<State> = async (context, next) => {\n const queryRunner = KoalApp.getInstance().getDatabaseConnection().createQueryRunner();\n context.state.queryRunner = queryRunner;\n queryRunner.startTransaction();\n try {\n await next();\n await queryRunner.commitTransaction();\n } catch (error) {\n await queryRunner.rollbackTransaction();\n throw error;\n } finally {\n await queryRunner.release();\n }\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kool-koala",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
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",
@@ -12,7 +12,7 @@
12
12
  "dev": "gulp --gulpfile build/gulpfile.ts dev",
13
13
  "compile": "gulp --gulpfile build/gulpfile.ts compile",
14
14
  "compile-release": "gulp --gulpfile build/gulpfile.ts compile-release",
15
- "test": "mocha --config tests/.mocharc.json",
15
+ "test": "TS_NODE_PROJECT=tsconfig.test.json mocha --config tests/.mocharc.json",
16
16
  "prepare": "husky",
17
17
  "postversion": "cp -r package.json .."
18
18
  },
@@ -43,6 +43,7 @@
43
43
  "@types/jsonwebtoken": "^9.0.9",
44
44
  "@types/mocha": "^10.0.10",
45
45
  "@types/yargs": "^17.0.33",
46
+ "axios": "^1.8.4",
46
47
  "chai": "^5.2.0",
47
48
  "commitizen": "^4.3.1",
48
49
  "cz-git": "^1.11.1",
@@ -74,6 +75,7 @@
74
75
  "koa-bodyparser": "^4.4.1",
75
76
  "koa-router": "^13.0.1",
76
77
  "koa-static": "^5.0.0",
78
+ "reflect-metadata": "^0.2.2",
77
79
  "typeorm": "^0.3.22"
78
80
  }
79
81
  }
@@ -17,7 +17,7 @@ class AuthorizationService {
17
17
  }
18
18
  userHasRight(user, permission) {
19
19
  return __awaiter(this, void 0, void 0, function* () {
20
- user = (yield common_1.KoalApp.getInstance().getConfiguration().getUserRepository().findOne({
20
+ user = (yield common_1.KoalApp.getInstance().getConfiguration().getUserRepository().getOneWhere({
21
21
  where: {
22
22
  id: user.id
23
23
  },
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/../src/services/authorization-service.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,6EAAyE;AAEzE,sCAAoC;AAEpC,MAAa,oBAAoB;IAI/B;IACA,CAAC;IACK,YAAY,CAAC,IAAO,EAAE,UAAa;;YACvC,IAAI,IAAM,MAAM,gBAAO,CAAC,WAAW,EAAE,CAAC,gBAAgB,EAAE,CAAC,iBAAiB,EAAE,CAAC,OAAO,CAAC;gBACnF,KAAK,EAAuB;oBAC1B,EAAE,EAAE,IAAI,CAAC,EAAE;iBACZ;gBACD,SAAS,EAA2B;oBAClC,WAAW,EAAE,IAAI;iBAClB;aACF,CAAC,CAAA,CAAC;YACH,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,UAAU,CAAC,EAAE,CAAC;gBAC3D,MAAM,IAAI,wCAAkB,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;YACjD,CAAC;QACH,CAAC;KAAA;CACF;AAnBD,oDAmBC","file":"authorization-service.js","sourcesContent":["import { FindOptionsRelations, FindOptionsWhere, Repository } from 'typeorm';\nimport { AuthorizationError } from '../types/errors/authorization-error';\nimport { AuthenticableEntity } from '../types';\nimport { KoalApp } from '../common';\n\nexport class AuthorizationService<\n U extends AuthenticableEntity,\n P\n> {\n constructor() {\n }\n async userHasRight(user: U, permission: P) {\n user = <U>await KoalApp.getInstance().getConfiguration().getUserRepository().findOne({\n where: <FindOptionsWhere<U>>{\n id: user.id\n },\n relations: <FindOptionsRelations<U>>{\n permissions: true\n }\n });\n if (!user.permissions.some((p) => p.textId === permission)) {\n throw new AuthorizationError(user, permission);\n }\n }\n}"]}
1
+ {"version":3,"sources":["../src/../src/services/authorization-service.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,6EAAyE;AAEzE,sCAAoC;AAEpC,MAAa,oBAAoB;IAI/B;IACA,CAAC;IACK,YAAY,CAAC,IAAO,EAAE,UAAa;;YACvC,IAAI,IAAM,MAAM,gBAAO,CAAC,WAAW,EAAE,CAAC,gBAAgB,EAAE,CAAC,iBAAiB,EAAE,CAAC,WAAW,CAAC;gBACvF,KAAK,EAAuB;oBAC1B,EAAE,EAAE,IAAI,CAAC,EAAE;iBACZ;gBACD,SAAS,EAA2B;oBAClC,WAAW,EAAE,IAAI;iBAClB;aACF,CAAC,CAAA,CAAC;YACH,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,UAAU,CAAC,EAAE,CAAC;gBAC3D,MAAM,IAAI,wCAAkB,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;YACjD,CAAC;QACH,CAAC;KAAA;CACF;AAnBD,oDAmBC","file":"authorization-service.js","sourcesContent":["import { FindOptionsRelations, FindOptionsWhere, Repository } from 'typeorm';\nimport { AuthorizationError } from '../types/errors/authorization-error';\nimport { AuthenticableEntity } from '../types';\nimport { KoalApp } from '../common';\n\nexport class AuthorizationService<\n U extends AuthenticableEntity,\n P\n> {\n constructor() {\n }\n async userHasRight(user: U, permission: P) {\n user = <U>await KoalApp.getInstance().getConfiguration().getUserRepository().getOneWhere({\n where: <FindOptionsWhere<U>>{\n id: user.id\n },\n relations: <FindOptionsRelations<U>>{\n permissions: true\n }\n });\n if (!user.permissions.some((p) => p.textId === permission)) {\n throw new AuthorizationError(user, permission);\n }\n }\n}"]}
@@ -0,0 +1,3 @@
1
+ import { ParameterizedContext } from "koa";
2
+ import { State } from "./state";
3
+ export type Context = ParameterizedContext<State>;
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+
4
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/../src/types/common/context.ts"],"names":[],"mappings":"","file":"context.js","sourcesContent":["import { ParameterizedContext } from \"koa\";\nimport { State } from \"./state\";\n\nexport type Context = ParameterizedContext<State>;"]}
@@ -0,0 +1,6 @@
1
+ import { QueryRunner } from "typeorm";
2
+ import { AuthenticableEntity } from "../entities";
3
+ export interface State {
4
+ user?: AuthenticableEntity;
5
+ queryRunner: QueryRunner;
6
+ }
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+
4
+ //# sourceMappingURL=state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/../src/types/common/state.ts"],"names":[],"mappings":"","file":"state.js","sourcesContent":["import { QueryRunner } from \"typeorm\";\nimport { AuthenticableEntity } from \"../entities\";\n\nexport interface State {\n user?: AuthenticableEntity;\n queryRunner: QueryRunner;\n}"]}