chyz 2.0.1-rc.3 → 2.0.1-rc.36

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 (229) hide show
  1. package/BaseChyz.ts +623 -0
  2. package/README.md +518 -518
  3. package/base/ActionFilter.ts +88 -0
  4. package/base/BadRequestHttpException.ts +14 -0
  5. package/base/{BaseError.js → BaseError.ts} +26 -18
  6. package/base/Behavior.ts +6 -0
  7. package/base/CBaseObject.ts +17 -0
  8. package/base/CEvents.ts +24 -0
  9. package/base/{CRequest.js → CRequest.ts} +6 -2
  10. package/base/CWebController.ts +90 -0
  11. package/base/Component.ts +66 -0
  12. package/{model/RouteDefinition.js → base/Configurable.ts} +4 -2
  13. package/base/DataErrorDbException.ts +16 -0
  14. package/base/DbConnection.ts +55 -0
  15. package/base/ForbiddenHttpException.ts +15 -0
  16. package/base/InvalidArgumentException.ts +16 -0
  17. package/base/InvalidConfigException.ts +16 -0
  18. package/base/{Logs.js → Logs.ts} +41 -24
  19. package/base/{Model.js → Model.ts} +225 -158
  20. package/base/{ModelManager.js → ModelManager.ts} +7 -7
  21. package/base/NotFoundHttpException.ts +14 -0
  22. package/base/RestClient.ts +26 -0
  23. package/base/UnauthorizedHttpException.ts +17 -0
  24. package/base/ValidationHttpException.ts +14 -0
  25. package/base/db/Exception.ts +14 -0
  26. package/base/index.ts +19 -0
  27. package/decorator/Middleware.ts +9 -0
  28. package/decorator/{controller.js → controller.ts} +7 -9
  29. package/decorator/{delete.js → delete.ts} +9 -9
  30. package/decorator/enums/ControllerDecoratorParams.ts +5 -0
  31. package/decorator/{get.js → get.ts} +11 -10
  32. package/decorator/index.ts +5 -0
  33. package/decorator/{post.js → post.ts} +10 -10
  34. package/decorator/{put.js → put.ts} +9 -9
  35. package/filters/AccessControl.ts +74 -0
  36. package/filters/AccessRule.ts +182 -0
  37. package/filters/auth/{AuthInterface.d.ts → AuthInterface.ts} +15 -7
  38. package/filters/auth/AuthMethod.ts +100 -0
  39. package/filters/auth/HttpBasicAuth.ts +79 -0
  40. package/filters/auth/HttpBearerAuth.ts +34 -0
  41. package/filters/auth/HttpHeaderAuth.ts +61 -0
  42. package/filters/auth/JwtHttpBearerAuth.ts +83 -0
  43. package/filters/auth/KeyCloakHttpBearerAuth.ts +114 -0
  44. package/filters/auth/index.ts +4 -0
  45. package/filters/index.ts +2 -0
  46. package/index.ts +80 -0
  47. package/log/config/log4js.json +55 -55
  48. package/model/RouteDefinition.ts +18 -0
  49. package/package.json +63 -61
  50. package/rbac/AuthAssignment.ts +50 -0
  51. package/rbac/{AuthItem.js → AuthItem.ts} +22 -16
  52. package/rbac/{AuthItemChild.js → AuthItemChild.ts} +21 -14
  53. package/rbac/AuthManager.ts +399 -0
  54. package/rbac/index.ts +12 -0
  55. package/{web/IdentityInterface.js → requiments/Glob.ts} +3 -2
  56. package/requiments/{ReflectUtil.js → ReflectUtil.ts} +6 -4
  57. package/requiments/{Utils.js → Utils.ts} +40 -34
  58. package/validators/BooleanValidator.ts +0 -0
  59. package/validators/CompareValidator.ts +0 -0
  60. package/validators/DateValidator.ts +0 -0
  61. package/validators/EmailValidator.ts +0 -0
  62. package/validators/Validator.ts +27 -0
  63. package/web/{IdentityInterface.d.ts → IdentityInterface.ts} +15 -2
  64. package/web/WebUser.ts +187 -0
  65. package/BaseChyz.d.ts +0 -74
  66. package/BaseChyz.d.ts.map +0 -1
  67. package/BaseChyz.js +0 -569
  68. package/base/ActionFilter.d.ts +0 -33
  69. package/base/ActionFilter.d.ts.map +0 -1
  70. package/base/ActionFilter.js +0 -90
  71. package/base/BadRequestHttpException.d.ts +0 -6
  72. package/base/BadRequestHttpException.d.ts.map +0 -1
  73. package/base/BadRequestHttpException.js +0 -17
  74. package/base/BaseError.d.ts +0 -44
  75. package/base/BaseError.d.ts.map +0 -1
  76. package/base/Behavior.d.ts +0 -4
  77. package/base/Behavior.d.ts.map +0 -1
  78. package/base/Behavior.js +0 -7
  79. package/base/CBaseObject.d.ts +0 -5
  80. package/base/CBaseObject.d.ts.map +0 -1
  81. package/base/CBaseObject.js +0 -16
  82. package/base/CEvents.d.ts +0 -13
  83. package/base/CEvents.d.ts.map +0 -1
  84. package/base/CEvents.js +0 -24
  85. package/base/CRequest.d.ts +0 -2
  86. package/base/CRequest.d.ts.map +0 -1
  87. package/base/CWebController.d.ts +0 -44
  88. package/base/CWebController.d.ts.map +0 -1
  89. package/base/CWebController.js +0 -81
  90. package/base/Component.d.ts +0 -21
  91. package/base/Component.d.ts.map +0 -1
  92. package/base/Component.js +0 -57
  93. package/base/Configurable.d.ts +0 -3
  94. package/base/Configurable.d.ts.map +0 -1
  95. package/base/Configurable.js +0 -8
  96. package/base/DataErrorDbException.d.ts +0 -6
  97. package/base/DataErrorDbException.d.ts.map +0 -1
  98. package/base/DataErrorDbException.js +0 -17
  99. package/base/DbConnection.d.ts +0 -13
  100. package/base/DbConnection.d.ts.map +0 -1
  101. package/base/DbConnection.js +0 -53
  102. package/base/ForbiddenHttpException.d.ts +0 -5
  103. package/base/ForbiddenHttpException.d.ts.map +0 -1
  104. package/base/ForbiddenHttpException.js +0 -16
  105. package/base/InvalidArgumentException.d.ts +0 -6
  106. package/base/InvalidArgumentException.d.ts.map +0 -1
  107. package/base/InvalidArgumentException.js +0 -17
  108. package/base/InvalidConfigException.d.ts +0 -6
  109. package/base/InvalidConfigException.d.ts.map +0 -1
  110. package/base/InvalidConfigException.js +0 -17
  111. package/base/Logs.d.ts +0 -22
  112. package/base/Logs.d.ts.map +0 -1
  113. package/base/Model.d.ts +0 -302
  114. package/base/Model.d.ts.map +0 -1
  115. package/base/ModelManager.d.ts +0 -2
  116. package/base/ModelManager.d.ts.map +0 -1
  117. package/base/NotFoundHttpException.d.ts +0 -6
  118. package/base/NotFoundHttpException.d.ts.map +0 -1
  119. package/base/NotFoundHttpException.js +0 -17
  120. package/base/RestClient.d.ts +0 -7
  121. package/base/RestClient.d.ts.map +0 -1
  122. package/base/RestClient.js +0 -25
  123. package/base/UnauthorizedHttpException.d.ts +0 -6
  124. package/base/UnauthorizedHttpException.d.ts.map +0 -1
  125. package/base/UnauthorizedHttpException.js +0 -17
  126. package/base/ValidationHttpException.d.ts +0 -6
  127. package/base/ValidationHttpException.d.ts.map +0 -1
  128. package/base/ValidationHttpException.js +0 -17
  129. package/base/db/Exception.d.ts +0 -7
  130. package/base/db/Exception.d.ts.map +0 -1
  131. package/base/db/Exception.js +0 -15
  132. package/base/index.d.ts +0 -20
  133. package/base/index.d.ts.map +0 -1
  134. package/base/index.js +0 -41
  135. package/decorator/Middleware.d.ts +0 -4
  136. package/decorator/Middleware.d.ts.map +0 -1
  137. package/decorator/Middleware.js +0 -11
  138. package/decorator/controller.d.ts +0 -3
  139. package/decorator/controller.d.ts.map +0 -1
  140. package/decorator/delete.d.ts +0 -3
  141. package/decorator/delete.d.ts.map +0 -1
  142. package/decorator/enums/ControllerDecoratorParams.d.ts +0 -6
  143. package/decorator/enums/ControllerDecoratorParams.d.ts.map +0 -1
  144. package/decorator/enums/ControllerDecoratorParams.js +0 -9
  145. package/decorator/get.d.ts +0 -3
  146. package/decorator/get.d.ts.map +0 -1
  147. package/decorator/index.d.ts +0 -6
  148. package/decorator/index.d.ts.map +0 -1
  149. package/decorator/index.js +0 -13
  150. package/decorator/post.d.ts +0 -3
  151. package/decorator/post.d.ts.map +0 -1
  152. package/decorator/put.d.ts +0 -3
  153. package/decorator/put.d.ts.map +0 -1
  154. package/filters/AccessControl.d.ts +0 -13
  155. package/filters/AccessControl.d.ts.map +0 -1
  156. package/filters/AccessControl.js +0 -83
  157. package/filters/AccessRule.d.ts +0 -83
  158. package/filters/AccessRule.d.ts.map +0 -1
  159. package/filters/AccessRule.js +0 -136
  160. package/filters/auth/AuthInterface.d.ts.map +0 -1
  161. package/filters/auth/AuthInterface.js +0 -2
  162. package/filters/auth/AuthMethod.d.ts +0 -38
  163. package/filters/auth/AuthMethod.d.ts.map +0 -1
  164. package/filters/auth/AuthMethod.js +0 -82
  165. package/filters/auth/HttpBasicAuth.d.ts +0 -24
  166. package/filters/auth/HttpBasicAuth.d.ts.map +0 -1
  167. package/filters/auth/HttpBasicAuth.js +0 -78
  168. package/filters/auth/HttpBearerAuth.d.ts +0 -18
  169. package/filters/auth/HttpBearerAuth.d.ts.map +0 -1
  170. package/filters/auth/HttpBearerAuth.js +0 -33
  171. package/filters/auth/HttpHeaderAuth.d.ts +0 -19
  172. package/filters/auth/HttpHeaderAuth.d.ts.map +0 -1
  173. package/filters/auth/HttpHeaderAuth.js +0 -64
  174. package/filters/auth/JwtHttpBearerAuth.d.ts +0 -21
  175. package/filters/auth/JwtHttpBearerAuth.d.ts.map +0 -1
  176. package/filters/auth/JwtHttpBearerAuth.js +0 -87
  177. package/filters/auth/KeyCloakHttpBearerAuth.d.ts +0 -23
  178. package/filters/auth/KeyCloakHttpBearerAuth.d.ts.map +0 -1
  179. package/filters/auth/KeyCloakHttpBearerAuth.js +0 -116
  180. package/filters/auth/index.d.ts +0 -5
  181. package/filters/auth/index.d.ts.map +0 -1
  182. package/filters/auth/index.js +0 -11
  183. package/filters/index.d.ts +0 -3
  184. package/filters/index.d.ts.map +0 -1
  185. package/filters/index.js +0 -7
  186. package/index.d.ts +0 -26
  187. package/index.d.ts.map +0 -1
  188. package/index.js +0 -72
  189. package/model/RouteDefinition.d.ts +0 -7
  190. package/model/RouteDefinition.d.ts.map +0 -1
  191. package/rbac/AuthAssignment.d.ts +0 -19
  192. package/rbac/AuthAssignment.d.ts.map +0 -1
  193. package/rbac/AuthAssignment.js +0 -44
  194. package/rbac/AuthItem.d.ts +0 -27
  195. package/rbac/AuthItem.d.ts.map +0 -1
  196. package/rbac/AuthItemChild.d.ts +0 -19
  197. package/rbac/AuthItemChild.d.ts.map +0 -1
  198. package/rbac/AuthManager.d.ts +0 -112
  199. package/rbac/AuthManager.d.ts.map +0 -1
  200. package/rbac/AuthManager.js +0 -356
  201. package/rbac/index.d.ts +0 -5
  202. package/rbac/index.d.ts.map +0 -1
  203. package/rbac/index.js +0 -28
  204. package/requiments/Glob.d.ts +0 -3
  205. package/requiments/Glob.d.ts.map +0 -1
  206. package/requiments/Glob.js +0 -10
  207. package/requiments/ReflectUtil.d.ts +0 -1
  208. package/requiments/ReflectUtil.d.ts.map +0 -1
  209. package/requiments/Utils.d.ts +0 -2
  210. package/requiments/Utils.d.ts.map +0 -1
  211. package/validators/BooleanValidator.d.ts +0 -1
  212. package/validators/BooleanValidator.d.ts.map +0 -1
  213. package/validators/BooleanValidator.js +0 -1
  214. package/validators/CompareValidator.d.ts +0 -1
  215. package/validators/CompareValidator.d.ts.map +0 -1
  216. package/validators/CompareValidator.js +0 -1
  217. package/validators/DateValidator.d.ts +0 -1
  218. package/validators/DateValidator.d.ts.map +0 -1
  219. package/validators/DateValidator.js +0 -1
  220. package/validators/EmailValidator.d.ts +0 -1
  221. package/validators/EmailValidator.d.ts.map +0 -1
  222. package/validators/EmailValidator.js +0 -1
  223. package/validators/Validator.d.ts +0 -18
  224. package/validators/Validator.d.ts.map +0 -1
  225. package/validators/Validator.js +0 -27
  226. package/web/IdentityInterface.d.ts.map +0 -1
  227. package/web/WebUser.d.ts +0 -72
  228. package/web/WebUser.d.ts.map +0 -1
  229. package/web/WebUser.js +0 -165
package/BaseChyz.ts ADDED
@@ -0,0 +1,623 @@
1
+ /**
2
+ * https server
3
+ */
4
+ import express, {NextFunction, Request, Response} from "express";
5
+ import {createServer as httpsCreate} from "https";
6
+ import {createServer as httpCreate} from "http";
7
+
8
+ /**
9
+ * Freamwork
10
+ */
11
+ import {BaseError, CEvents, CWebController, InvalidConfigException, Logs, ModelManager} from "./base";
12
+ import {Utils} from "./requiments/Utils";
13
+ import calendar from "dayjs/plugin/calendar";
14
+ import weekOfYear from "dayjs/plugin/weekOfYear";
15
+ import isTomorrow from "dayjs/plugin/isTomorrow";
16
+ import {RouteDefinition} from "./model/RouteDefinition";
17
+ import bodyParser = require('body-parser');
18
+ import fs = require("fs");
19
+
20
+
21
+ // const http_request = require('debug')('http:request')
22
+ // const http_request_body = http_request.extend('body')
23
+ // const http_request_headers = http_request.extend('headers')
24
+ import compression from 'compression';
25
+
26
+ // const fs = require('fs');
27
+
28
+
29
+ import ip from 'ip';
30
+ import cors from 'cors';
31
+
32
+ import methodOverride from 'method-override';
33
+ const Server = express();
34
+ const emitter = require('events').EventEmitter;
35
+ const em = new emitter();
36
+
37
+ /**
38
+ * set request id
39
+ */
40
+ Object.defineProperty(Server.request, 'reqId', {
41
+ configurable: true,
42
+ enumerable: true,
43
+ writable: true
44
+ })
45
+ Object.defineProperty(Server.request, 'user', {
46
+ configurable: true,
47
+ enumerable: true,
48
+ writable: true
49
+ })
50
+ Object.defineProperty(Server.request, 'identity', {
51
+ configurable: true,
52
+ enumerable: true,
53
+ writable: true
54
+ })
55
+
56
+
57
+ import validate from 'validate.js';
58
+ import dayjs from 'dayjs';
59
+ import utc from 'dayjs/plugin/utc';
60
+ import relative from 'dayjs/plugin/relativeTime';
61
+
62
+ dayjs.extend(utc)
63
+ dayjs.extend(relative)
64
+ dayjs.extend(isTomorrow);
65
+ dayjs.extend(calendar);
66
+ dayjs.extend(weekOfYear);
67
+
68
+ /**
69
+ * Use
70
+ * selectedBox: {
71
+ * array: {
72
+ * id: {
73
+ * numericality: {
74
+ * onlyInteger: true,
75
+ * greaterThan: 0
76
+ * }
77
+ * }
78
+ * }
79
+ * },
80
+ * @param arrayItems
81
+ * @param itemConstraints
82
+ */
83
+
84
+
85
+ validate.validators.array = (arrayItems: any, itemConstraints: any) => {
86
+ if (!Utils.isArray(arrayItems)) return {errors: [{error: 'in not array'}]};
87
+ const arrayItemErrors = arrayItems.reduce((errors: any, item: any, index: any) => {
88
+ const error = validate(item, itemConstraints);
89
+ if (error) errors[index] = {error: error};
90
+ return errors;
91
+ }, {});
92
+
93
+ return Utils.isEmpty(arrayItemErrors) ? null : {errors: arrayItemErrors};
94
+ };
95
+ validate.validators.tokenString = (items: any, itemConstraints: any) => {
96
+ let arrayItems = items.split(",");
97
+ const arrayItemErrors = arrayItems.reduce((errors: any, item: any, index: any) => {
98
+ const error = validate(item, itemConstraints);
99
+ if (error) errors[index] = {error: error};
100
+ return errors;
101
+ }, {});
102
+
103
+ return Utils.isEmpty(arrayItemErrors) ? null : {errors: arrayItemErrors};
104
+ };
105
+
106
+
107
+ validate.extend(validate.validators.datetime, {
108
+ // The value is guaranteed not to be null or undefined but otherwise it
109
+ // could be anything.
110
+ parse: function (value: any, options: any) {
111
+ return +dayjs().utc(value);
112
+ },
113
+ // Input is a unix timestamp
114
+ format: function (value: any, options: any) {
115
+ const format = options.dateOnly ? "YYYY-MM-DD" : "YYYY-MM-DD hh:mm:ss";
116
+ return dayjs().utc(value).format(format);
117
+ }
118
+ });
119
+
120
+ interface BaseChyzConfig {
121
+ port: string;
122
+ logs: string;
123
+ components: string;
124
+ staticFilePath?: string
125
+ }
126
+
127
+
128
+ export default class BaseChyz {
129
+ private config: BaseChyzConfig | any;
130
+ static httpServer: any;
131
+ static propvider: any = Server
132
+ private _port: number = 3001;
133
+ static db: any;
134
+ static date: any = dayjs;
135
+ static routes: any;
136
+ static logs: Logs = new Logs();
137
+ private static _validate: any = validate;
138
+ private _controllerpath: string = "Controllers"
139
+ private static controllers: Array<CWebController> = []
140
+ public static components: any = {}
141
+ public static middlewares: any = {}
142
+ private static _EventEmitter: any = em
143
+
144
+
145
+ static get EventEmitter(): any {
146
+ return this._EventEmitter;
147
+ }
148
+
149
+ static set EventEmitter(value: any) {
150
+ this._EventEmitter = value;
151
+ }
152
+
153
+ get controllerpath(): string {
154
+ return this._controllerpath;
155
+ }
156
+
157
+ set controllerpath(value: string) {
158
+ this._controllerpath = value;
159
+ }
160
+
161
+ /**
162
+ *
163
+ */
164
+ async init() {
165
+
166
+ /**
167
+ * server port setting
168
+ */
169
+ if (this.config.hasOwnProperty("port"))
170
+ this.port = this.config.port;
171
+
172
+ /**
173
+ * controller path
174
+ */
175
+ if (this.config.controllerpath) {
176
+ this.controllerpath = this.config.controllerpath
177
+ }
178
+
179
+
180
+ /**
181
+ * Model Register
182
+ */
183
+
184
+ this.loadModels();
185
+
186
+ /**
187
+ * Express Server
188
+ */
189
+ this.middleware()
190
+
191
+ /**
192
+ * Load Controller
193
+ */
194
+ await this.loadController();
195
+
196
+
197
+ }
198
+
199
+ /**
200
+ * Listen port number
201
+ * Server port number get
202
+ */
203
+ get port(): number {
204
+ return this._port;
205
+ }
206
+
207
+ /**
208
+ * Listen port number
209
+ * Server port number setting
210
+ * @param value
211
+ */
212
+ set port(value: number) {
213
+ this._port = value;
214
+ }
215
+
216
+
217
+ static get validate(): any {
218
+ return this._validate;
219
+ }
220
+
221
+ static set validate(value: any) {
222
+ this._validate = value;
223
+ }
224
+
225
+ async app(config: any = {}): Promise<BaseChyz> {
226
+
227
+ BaseChyz.EventEmitter.emit(CEvents.ON_INIT_BEFORE, this, config)
228
+
229
+ /**
230
+ * Config set
231
+ */
232
+ this.config = config;
233
+
234
+
235
+ /**
236
+ * log setting
237
+ */
238
+ if (this.config.logs instanceof Logs) {
239
+ BaseChyz.logs = this.config.logs;
240
+ } else if (!this.config.hasOwnProperty('logs')) {
241
+ BaseChyz.logs = new Logs();
242
+ }
243
+
244
+
245
+ let components = Utils.findKeyValue(config, "components")
246
+ if (components) {
247
+
248
+ /**
249
+ * first initial database component
250
+ */
251
+ if (components.db) {
252
+ let comp = components['db'];
253
+ BaseChyz.debug("First initial database component ", "db")
254
+ try {
255
+ BaseChyz.components["db"] = Utils.createObject(new comp.class, comp);
256
+ BaseChyz.components["db"]?.init();
257
+ delete components.db
258
+ } catch (e) {
259
+ BaseChyz.error("Create Component Error", e)
260
+ }
261
+ }
262
+
263
+ for (const componentsKey in components) {
264
+
265
+ let comp = components[componentsKey];
266
+ BaseChyz.debug("Create Component ", componentsKey)
267
+ try {
268
+ BaseChyz.components[componentsKey] = Utils.createObject(new comp.class, comp);
269
+ BaseChyz.components[componentsKey]?.init();
270
+ } catch (e) {
271
+ BaseChyz.error("Create Component Error", e)
272
+ }
273
+
274
+ }
275
+ }
276
+
277
+
278
+ let middlewares = Utils.findKeyValue(config, "middlewares")
279
+ if (middlewares) {
280
+ for (const middlewareKey in middlewares) {
281
+ let middleware1 = middlewares[middlewareKey];
282
+ BaseChyz.debug("Create middlewares ", middlewareKey)
283
+ BaseChyz.middlewares[middlewareKey] = middleware1;
284
+ // BaseChyz.middlewares[middlewareKey] = Utils.createObject(new middleware1.class, middleware1);
285
+ }
286
+ }
287
+
288
+ await this.init();
289
+
290
+ BaseChyz.EventEmitter.emit(CEvents.ON_INIT_AFTER, this, config)
291
+ return this;
292
+ }
293
+
294
+
295
+ public static trace(...args: any[]) {
296
+ BaseChyz.logs.fatal(...arguments)
297
+ }
298
+
299
+ public static debug(...args: any[]) {
300
+ BaseChyz.logs.debug(...args)
301
+ }
302
+
303
+ public static info(...args: any[]) {
304
+ BaseChyz.logs.info(...args)
305
+ }
306
+
307
+ public static warn(...args: any[]) {
308
+ BaseChyz.logs.warn(...args)
309
+ }
310
+
311
+ public static error(...args: any[]) {
312
+ BaseChyz.logs.error(...args)
313
+ }
314
+
315
+ public static fatal(...args: any[]) {
316
+ BaseChyz.logs.fatal(...args)
317
+ }
318
+
319
+
320
+ public static warning(...args: any[]) {
321
+ BaseChyz.logs.warn(...args)
322
+ }
323
+
324
+ public static t(text: string, params?: any) {
325
+ if (text == "") return;
326
+
327
+ // let lang = require("@root/locales/tr/translation.json");
328
+ let lang: any = {};
329
+ if (lang.hasOwnProperty(text)) {
330
+ text = lang[text];
331
+ }
332
+
333
+ return text.tokenReplace(params);
334
+ }
335
+
336
+
337
+ public errorLogger(error: any, req: any, res: any, next: any) { // for logging errors
338
+ BaseChyz.error(error)
339
+ next(error) // forward to next middleware
340
+ }
341
+
342
+ public errorResponder(error: any, req: any, res: any, next: any) { // responding to client
343
+ if (error.type == 'redirect')
344
+ res.redirect('/error')
345
+ else if (error.type == 'time-out') // arbitrary condition check
346
+ res.status(408).json(error)
347
+ else
348
+ next(error) // forwarding exceptional case to fail-safe middleware
349
+ }
350
+
351
+
352
+ public errorHandler(err: any, req: any, res: any, next: any) {
353
+ if (res.headersSent) {
354
+ return next(err)
355
+ }
356
+
357
+ res.status(500).json({error: err})
358
+ }
359
+
360
+ public static getComponent(key: any) {
361
+ return BaseChyz.components[key] ?? null
362
+ }
363
+
364
+
365
+ public static getMiddlewares(key: any) {
366
+ return BaseChyz.middlewares[key] ?? null
367
+ }
368
+
369
+ /**
370
+ * load model
371
+ */
372
+ loadModels() {
373
+ let models: any = {}
374
+ let path = `${this._controllerpath}/../Models`;
375
+ if (fs.existsSync(path)) {
376
+ fs.readdirSync(path).forEach((file: string) => {
377
+ if (file !== "index.ts") {
378
+ let model = require(`${path}/${file}`);
379
+ // @ts-ignore
380
+ let className = file.split(".")[0] + "Class";
381
+ if (model[className])
382
+ models[className.replace("Class", "")] = new model[className];
383
+ }
384
+ })
385
+
386
+ /**
387
+ *
388
+ */
389
+ ModelManager._register(models);
390
+
391
+ for (const key of Object.keys(ModelManager)) {
392
+ if (key != "_register") {
393
+ ModelManager[key].init();
394
+ }
395
+ }
396
+ }else{
397
+ BaseChyz.error("Model folder not found");
398
+ }
399
+ }
400
+
401
+
402
+ async beforeMiddleware(req: Request, res: Response, next: NextFunction, instance: CWebController, route: RouteDefinition) {
403
+ BaseChyz.debug(`${instance.id}/${route.path}->beforeMiddleware trigger`);
404
+ // http_request_body("Request body " + JSON.stringify(req.body))
405
+ // http_request_headers("Request header " + JSON.stringify(req.headers))
406
+ try {
407
+ await instance.beforeAction(route, req, res)
408
+ next();
409
+ } catch (e) {
410
+ BaseChyz.error(e)
411
+ if (e instanceof BaseError) {
412
+ res.status(e?.statusCode || 500)
413
+ res.json(e.toJSON())
414
+ } else {
415
+ res.json(e)
416
+ }
417
+
418
+ }
419
+
420
+ }
421
+
422
+ async responseHandler(req: Request, res: Response, next: NextFunction, instance: CWebController, route: RouteDefinition) {
423
+ BaseChyz.debug(`${instance.id}/${route.path}->responseHandler trigger`);
424
+ try {
425
+ // @ts-ignore
426
+ await instance[route.methodName](req, res, next);
427
+ next();
428
+ } catch (e) {
429
+ BaseChyz.error(e)
430
+ if (e instanceof BaseError) {
431
+ res.status(e?.statusCode || 500)
432
+ res.json(e.toJSON())
433
+ } else {
434
+ res.json(e)
435
+ }
436
+ }
437
+
438
+ }
439
+
440
+ async afterMiddleware(req: Request, res: Response, next: NextFunction, instance: CWebController, route: RouteDefinition) {
441
+ BaseChyz.debug(`${instance.id}/${route.path}->afterMiddleware trigger`);
442
+ try {
443
+ await instance.afterAction(route, req, res);
444
+ } catch (e) {
445
+ BaseChyz.error(e)
446
+ if (e instanceof BaseError) {
447
+ res.status(e?.statusCode || 500)
448
+ res.json(e.toJSON())
449
+ } else {
450
+ res.json(e)
451
+ }
452
+
453
+ }
454
+ }
455
+
456
+ /**
457
+ * load contoller
458
+ */
459
+ async loadController() {
460
+ // let articlesEndpoints: string[] = [];
461
+ for (const file of fs.readdirSync(`${this._controllerpath}/`)) {
462
+ // let controller = require(`${this._controllerpath}/${file}`);
463
+ let controller = (await import(`${this._controllerpath}/${file}`));
464
+ if (controller[file.replace(".ts", "")]) {
465
+ controller = controller[file.replace(".ts", "")]
466
+ } else if (controller.default) {
467
+ controller = controller.default;
468
+ } else {
469
+ throw new InvalidConfigException(BaseChyz.t(`Invalid Controller ${file}`))
470
+ }
471
+
472
+
473
+ // This is our instantiated class
474
+ const instance: CWebController = new controller();
475
+
476
+ BaseChyz.controllers.push(instance);
477
+
478
+ // The prefix saved to our controller
479
+ const prefix = Reflect.getMetadata('prefix', controller);
480
+ // Our `routes` array containing all our routes for this controller
481
+ const routes: Array<RouteDefinition> = Reflect.getMetadata('routes', controller);
482
+ BaseChyz.debug("Controller load ", controller.name, `(${prefix})`)
483
+
484
+ if (routes) {
485
+ routes.forEach(route => {
486
+ route.id = (route.path == "/" || route.path == "") ? instance.defaultAction : route.path;
487
+ BaseChyz.debug("Controller route Path", prefix + (route.path.startsWith("/") ? route.path : `/${route.path}`))
488
+ BaseChyz.propvider[route.requestMethod](prefix + (route.path.startsWith("/") ? route.path : `/${route.path}`),
489
+ (req: Request, res: Response, next: NextFunction) => this.beforeMiddleware(req, res, next, instance, route),
490
+ (req: Request, res: Response, next: NextFunction) => this.responseHandler(req, res, next, instance, route),
491
+ (req: Request, res: Response, next: NextFunction) => this.afterMiddleware(req, res, next, instance, route),
492
+ );
493
+ // BaseChyz.propvider[route.requestMethod](prefix + (route.path.startsWith("/") ? route.path : `/${route.path}`),
494
+ // async (req: Request, res: Response, next: NextFunction) => {
495
+ // try {
496
+ // BaseChyz.debug(`Call Request id ${actionId}`)
497
+ // http_request_body("Request body " + JSON.stringify(req.body))
498
+ // http_request_headers("Request header " + JSON.stringify(req.headers))
499
+ // await instance.beforeAction(route, req, res);
500
+ // next()
501
+ // } catch (e: any) {
502
+ //
503
+ // BaseChyz.error(e)
504
+ // if (e instanceof BaseError) {
505
+ // res.status(e?.statusCode || 500)
506
+ // res.json(e.toJSON())
507
+ // } else {
508
+ // res.json(e)
509
+ // }
510
+ //
511
+ // // / next(e)
512
+ // }
513
+ //
514
+ // },
515
+ // async (req: Request, res: Response, next: NextFunction) => {
516
+ // try {
517
+ // // @ts-ignore
518
+ // BaseChyz.debug("Request ID ", req.reqId)
519
+ // // @ts-ignore
520
+ // await instance[route.methodName](req, res, next);
521
+ // instance.afterAction(route, req, res);
522
+ // } catch (e) {
523
+ // BaseChyz.error(e)
524
+ // if (e instanceof BaseError) {
525
+ // res.status(e.statusCode || 500)
526
+ // res.json(e.toJSON())
527
+ // } else {
528
+ // res.json(e)
529
+ // }
530
+ // }
531
+ // })
532
+ });
533
+ }
534
+ }
535
+ }
536
+
537
+ public middleware() {
538
+
539
+ BaseChyz.propvider.use(bodyParser.json({limit: '1mb'}));
540
+ BaseChyz.propvider.use(bodyParser.urlencoded({limit: '1mb', extended: true})); // support encoded bodies
541
+ BaseChyz.propvider.use(methodOverride());
542
+ BaseChyz.propvider.use(cors());
543
+ //
544
+ // // CORS
545
+ // BaseChyz.express.use(function (req: any, res: Response, next: any) {
546
+ // // @ts-ignore
547
+ // req.reqId = Utils.uniqueId("chyzzzz_")
548
+ // res.setHeader('Content-Type', 'application/json');
549
+ // res.setHeader("Access-Control-Allow-Origin", "*");
550
+ // res.setHeader("Access-Control-Allow-Credentials", "true");
551
+ // res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
552
+ // res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,Authorization");
553
+ // next();
554
+ // });
555
+ //
556
+ // compress all responses
557
+ const shouldCompress = (req: Request, res: Response): boolean => {
558
+ // don't compress responses explicitly asking not
559
+ if (req.headers["x-no-compression"] || res.getHeader('Content-Type') === 'text/event-stream') {
560
+ return false;
561
+ }
562
+
563
+ // use compression filter function
564
+ // @ts-ignore
565
+ return compression.filter(req, res);
566
+ };
567
+ // @ts-ignore
568
+ BaseChyz.propvider.use(compression({filter: shouldCompress}))
569
+ //
570
+ // //static file path
571
+ if (this.config.staticFilePath) {
572
+ BaseChyz.info('Static file path', this.config.staticFilePath)
573
+ BaseChyz.propvider.use(express.static(this.config.staticFilePath))
574
+ }
575
+
576
+
577
+ //Middlewares
578
+ for (const middleware1 of Object.keys(BaseChyz.middlewares)) {
579
+ if (BaseChyz.middlewares[middleware1]?.keycloak) {
580
+ let keycloak = BaseChyz.middlewares[middleware1].keycloak;
581
+ //@ts-ignore
582
+ BaseChyz.propvider.use(keycloak.middleware(BaseChyz.middlewares[middleware1].config));
583
+ } else {
584
+ BaseChyz.propvider.use(BaseChyz.middlewares[middleware1]);
585
+ }
586
+
587
+ }
588
+
589
+
590
+ BaseChyz.propvider.use(this.errorResponder)
591
+ BaseChyz.propvider.use(this.errorHandler)
592
+
593
+ BaseChyz.EventEmitter.emit(CEvents.ON_MIDDLEWARE, this)
594
+ }
595
+
596
+ public Start() {
597
+
598
+ BaseChyz.info("Express Server Starting")
599
+ BaseChyz.EventEmitter.emit(CEvents.ON_BEFORE_START, this)
600
+ if (this.config?.ssl) {
601
+ BaseChyz.httpServer = httpsCreate(this.config?.ssl, BaseChyz.propvider);
602
+ BaseChyz.httpServer.listen(this._port, () => {
603
+ BaseChyz.info("Express Server Start ")
604
+ BaseChyz.info(`Liten Port ${this._port}`)
605
+ BaseChyz.info(`https://localhost:${this._port}`)
606
+ BaseChyz.info(`https://${ip.address()}:${this._port}`)
607
+ BaseChyz.EventEmitter.emit(CEvents.ON_START, this)
608
+ })
609
+ } else {
610
+ BaseChyz.httpServer = httpCreate(BaseChyz.propvider);
611
+ BaseChyz.httpServer.listen(this._port, () => {
612
+ BaseChyz.info("Express Server Start ")
613
+ BaseChyz.info(`Liten Port ${this._port}`)
614
+ BaseChyz.info(`http://localhost:${this._port}`)
615
+ BaseChyz.info(`http://${ip.address()}:${this._port}`)
616
+ BaseChyz.EventEmitter.emit(CEvents.ON_START, this)
617
+ })
618
+ }
619
+
620
+
621
+ return this;
622
+ }
623
+ }