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.js DELETED
@@ -1,569 +0,0 @@
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- var __importDefault = (this && this.__importDefault) || function (mod) {
35
- return (mod && mod.__esModule) ? mod : { "default": mod };
36
- };
37
- Object.defineProperty(exports, "__esModule", { value: true });
38
- /**
39
- * https server
40
- */
41
- const express_1 = __importDefault(require("express"));
42
- const https_1 = require("https");
43
- const http_1 = require("http");
44
- /**
45
- * Freamwork
46
- */
47
- const base_1 = require("./base");
48
- const Utils_1 = require("./requiments/Utils");
49
- const calendar_1 = __importDefault(require("dayjs/plugin/calendar"));
50
- const weekOfYear_1 = __importDefault(require("dayjs/plugin/weekOfYear"));
51
- const isTomorrow_1 = __importDefault(require("dayjs/plugin/isTomorrow"));
52
- const bodyParser = require("body-parser");
53
- const fs = require("fs");
54
- const http_request = require('debug')('http:request');
55
- const http_request_body = http_request.extend('body');
56
- const http_request_headers = http_request.extend('headers');
57
- const compression = require('compression');
58
- // const fs = require('fs');
59
- const ip = require('ip');
60
- const methodOverride = require('method-override');
61
- const Server = (0, express_1.default)();
62
- const cors = require('cors');
63
- const emitter = require('events').EventEmitter;
64
- const em = new emitter();
65
- /**
66
- * set request id
67
- */
68
- Object.defineProperty(Server.request, 'reqId', {
69
- configurable: true,
70
- enumerable: true,
71
- writable: true
72
- });
73
- Object.defineProperty(Server.request, 'user', {
74
- configurable: true,
75
- enumerable: true,
76
- writable: true
77
- });
78
- Object.defineProperty(Server.request, 'identity', {
79
- configurable: true,
80
- enumerable: true,
81
- writable: true
82
- });
83
- const validate = require('validate.js');
84
- const dayjs = require('dayjs');
85
- const utc = require('dayjs/plugin/utc');
86
- const relative = require('dayjs/plugin/relativeTime');
87
- dayjs.extend(utc);
88
- dayjs.extend(relative);
89
- dayjs.extend(isTomorrow_1.default);
90
- dayjs.extend(calendar_1.default);
91
- dayjs.extend(weekOfYear_1.default);
92
- /**
93
- * Use
94
- * selectedBox: {
95
- * array: {
96
- * id: {
97
- * numericality: {
98
- * onlyInteger: true,
99
- * greaterThan: 0
100
- * }
101
- * }
102
- * }
103
- * },
104
- * @param arrayItems
105
- * @param itemConstraints
106
- */
107
- validate.validators.array = (arrayItems, itemConstraints) => {
108
- if (!Utils_1.Utils.isArray(arrayItems))
109
- return { errors: [{ error: 'in not array' }] };
110
- const arrayItemErrors = arrayItems.reduce((errors, item, index) => {
111
- const error = validate(item, itemConstraints);
112
- if (error)
113
- errors[index] = { error: error };
114
- return errors;
115
- }, {});
116
- return Utils_1.Utils.isEmpty(arrayItemErrors) ? null : { errors: arrayItemErrors };
117
- };
118
- validate.validators.tokenString = (items, itemConstraints) => {
119
- let arrayItems = items.split(",");
120
- const arrayItemErrors = arrayItems.reduce((errors, item, index) => {
121
- const error = validate(item, itemConstraints);
122
- if (error)
123
- errors[index] = { error: error };
124
- return errors;
125
- }, {});
126
- return Utils_1.Utils.isEmpty(arrayItemErrors) ? null : { errors: arrayItemErrors };
127
- };
128
- validate.extend(validate.validators.datetime, {
129
- // The value is guaranteed not to be null or undefined but otherwise it
130
- // could be anything.
131
- parse: function (value, options) {
132
- return +dayjs().utc(value);
133
- },
134
- // Input is a unix timestamp
135
- format: function (value, options) {
136
- const format = options.dateOnly ? "YYYY-MM-DD" : "YYYY-MM-DD hh:mm:ss";
137
- return dayjs().utc(value).format(format);
138
- }
139
- });
140
- class BaseChyz {
141
- constructor() {
142
- this._port = 3001;
143
- this._controllerpath = "Controllers";
144
- }
145
- static get EventEmitter() {
146
- return this._EventEmitter;
147
- }
148
- static set EventEmitter(value) {
149
- this._EventEmitter = value;
150
- }
151
- get controllerpath() {
152
- return this._controllerpath;
153
- }
154
- set controllerpath(value) {
155
- this._controllerpath = value;
156
- }
157
- /**
158
- *
159
- */
160
- init() {
161
- return __awaiter(this, void 0, void 0, function* () {
162
- /**
163
- * server port setting
164
- */
165
- if (this.config.hasOwnProperty("port"))
166
- this.port = this.config.port;
167
- /**
168
- * controller path
169
- */
170
- if (this.config.controllerpath) {
171
- this.controllerpath = this.config.controllerpath;
172
- }
173
- /**
174
- * Model Register
175
- */
176
- this.loadModels();
177
- /**
178
- * Express Server
179
- */
180
- this.middleware();
181
- /**
182
- * Load Controller
183
- */
184
- yield this.loadController();
185
- });
186
- }
187
- /**
188
- * Listen port number
189
- * Server port number get
190
- */
191
- get port() {
192
- return this._port;
193
- }
194
- /**
195
- * Listen port number
196
- * Server port number setting
197
- * @param value
198
- */
199
- set port(value) {
200
- this._port = value;
201
- }
202
- static get validate() {
203
- return this._validate;
204
- }
205
- static set validate(value) {
206
- this._validate = value;
207
- }
208
- app(config = {}) {
209
- var _a, _b;
210
- return __awaiter(this, void 0, void 0, function* () {
211
- BaseChyz.EventEmitter.emit(base_1.CEvents.ON_INIT_BEFORE, this, config);
212
- /**
213
- * Config set
214
- */
215
- this.config = config;
216
- /**
217
- * log setting
218
- */
219
- if (this.config.logs instanceof base_1.Logs) {
220
- BaseChyz.logs = this.config.logs;
221
- }
222
- else if (!this.config.hasOwnProperty('logs')) {
223
- BaseChyz.logs = new base_1.Logs();
224
- }
225
- let components = Utils_1.Utils.findKeyValue(config, "components");
226
- if (components) {
227
- /**
228
- * first initial database component
229
- */
230
- if (components.db) {
231
- let comp = components['db'];
232
- BaseChyz.debug("First initial database component ", "db");
233
- try {
234
- BaseChyz.components["db"] = Utils_1.Utils.createObject(new comp.class, comp);
235
- (_a = BaseChyz.components["db"]) === null || _a === void 0 ? void 0 : _a.init();
236
- delete components.db;
237
- }
238
- catch (e) {
239
- BaseChyz.error("Create Component Error", e);
240
- }
241
- }
242
- for (const componentsKey in components) {
243
- let comp = components[componentsKey];
244
- BaseChyz.debug("Create Component ", componentsKey);
245
- try {
246
- BaseChyz.components[componentsKey] = Utils_1.Utils.createObject(new comp.class, comp);
247
- (_b = BaseChyz.components[componentsKey]) === null || _b === void 0 ? void 0 : _b.init();
248
- }
249
- catch (e) {
250
- BaseChyz.error("Create Component Error", e);
251
- }
252
- }
253
- }
254
- let middlewares = Utils_1.Utils.findKeyValue(config, "middlewares");
255
- if (middlewares) {
256
- for (const middlewareKey in middlewares) {
257
- let middleware1 = middlewares[middlewareKey];
258
- BaseChyz.debug("Create middlewares ", middlewareKey);
259
- BaseChyz.middlewares[middlewareKey] = middleware1;
260
- // BaseChyz.middlewares[middlewareKey] = Utils.createObject(new middleware1.class, middleware1);
261
- }
262
- }
263
- yield this.init();
264
- BaseChyz.EventEmitter.emit(base_1.CEvents.ON_INIT_AFTER, this, config);
265
- return this;
266
- });
267
- }
268
- static trace(...args) {
269
- BaseChyz.logs.fatal(...arguments);
270
- }
271
- static debug(...args) {
272
- BaseChyz.logs.debug(...args);
273
- }
274
- static info(...args) {
275
- BaseChyz.logs.info(...args);
276
- }
277
- static warn(...args) {
278
- BaseChyz.logs.warn(...args);
279
- }
280
- static error(...args) {
281
- BaseChyz.logs.error(...args);
282
- }
283
- static fatal(...args) {
284
- BaseChyz.logs.fatal(...args);
285
- }
286
- static warning(...args) {
287
- BaseChyz.logs.warn(...args);
288
- }
289
- static t(text, params) {
290
- if (text == "")
291
- return;
292
- // let lang = require("@root/locales/tr/translation.json");
293
- let lang = {};
294
- if (lang.hasOwnProperty(text)) {
295
- text = lang[text];
296
- }
297
- return text.tokenReplace(params);
298
- }
299
- errorLogger(error, req, res, next) {
300
- BaseChyz.error(error);
301
- next(error); // forward to next middleware
302
- }
303
- errorResponder(error, req, res, next) {
304
- if (error.type == 'redirect')
305
- res.redirect('/error');
306
- else if (error.type == 'time-out') // arbitrary condition check
307
- res.status(408).json(error);
308
- else
309
- next(error); // forwarding exceptional case to fail-safe middleware
310
- }
311
- errorHandler(err, req, res, next) {
312
- if (res.headersSent) {
313
- return next(err);
314
- }
315
- res.status(500).json({ error: err });
316
- }
317
- static getComponent(key) {
318
- var _a;
319
- return (_a = BaseChyz.components[key]) !== null && _a !== void 0 ? _a : null;
320
- }
321
- static getMiddlewares(key) {
322
- var _a;
323
- return (_a = BaseChyz.middlewares[key]) !== null && _a !== void 0 ? _a : null;
324
- }
325
- /**
326
- * load model
327
- */
328
- loadModels() {
329
- let models = {};
330
- let path = `${this._controllerpath}/../Models`;
331
- fs.readdirSync(path).forEach((file) => {
332
- if (file !== "index.ts") {
333
- let model = require(`${path}/${file}`);
334
- // @ts-ignore
335
- let className = file.split(".")[0] + "Class";
336
- if (model[className])
337
- models[className.replace("Class", "")] = new model[className];
338
- }
339
- });
340
- /**
341
- *
342
- */
343
- base_1.ModelManager._register(models);
344
- for (const key of Object.keys(base_1.ModelManager)) {
345
- if (key != "_register") {
346
- base_1.ModelManager[key].init();
347
- }
348
- }
349
- }
350
- beforeMiddleware(req, res, next, instance, route) {
351
- return __awaiter(this, void 0, void 0, function* () {
352
- BaseChyz.debug(`${instance.id}/${route.path}->beforeMiddleware trigger`);
353
- http_request_body("Request body " + JSON.stringify(req.body));
354
- http_request_headers("Request header " + JSON.stringify(req.headers));
355
- try {
356
- yield instance.beforeAction(route, req, res);
357
- next();
358
- }
359
- catch (e) {
360
- BaseChyz.error(e);
361
- if (e instanceof base_1.BaseError) {
362
- res.status((e === null || e === void 0 ? void 0 : e.statusCode) || 500);
363
- res.json(e.toJSON());
364
- }
365
- else {
366
- res.json(e);
367
- }
368
- }
369
- });
370
- }
371
- responseHandler(req, res, next, instance, route) {
372
- return __awaiter(this, void 0, void 0, function* () {
373
- BaseChyz.debug(`${instance.id}/${route.path}->responseHandler trigger`);
374
- try {
375
- // @ts-ignore
376
- yield instance[route.methodName](req, res, next);
377
- next();
378
- }
379
- catch (e) {
380
- BaseChyz.error(e);
381
- if (e instanceof base_1.BaseError) {
382
- res.status((e === null || e === void 0 ? void 0 : e.statusCode) || 500);
383
- res.json(e.toJSON());
384
- }
385
- else {
386
- res.json(e);
387
- }
388
- }
389
- });
390
- }
391
- afterMiddleware(req, res, next, instance, route) {
392
- return __awaiter(this, void 0, void 0, function* () {
393
- BaseChyz.debug(`${instance.id}/${route.path}->afterMiddleware trigger`);
394
- try {
395
- yield instance.afterAction(route, req, res);
396
- }
397
- catch (e) {
398
- BaseChyz.error(e);
399
- if (e instanceof base_1.BaseError) {
400
- res.status((e === null || e === void 0 ? void 0 : e.statusCode) || 500);
401
- res.json(e.toJSON());
402
- }
403
- else {
404
- res.json(e);
405
- }
406
- }
407
- });
408
- }
409
- /**
410
- * load contoller
411
- */
412
- loadController() {
413
- return __awaiter(this, void 0, void 0, function* () {
414
- // let articlesEndpoints: string[] = [];
415
- for (const file of fs.readdirSync(`${this._controllerpath}/`)) {
416
- // let controller = require(`${this._controllerpath}/${file}`);
417
- let controller = (yield Promise.resolve(`${`${this._controllerpath}/${file}`}`).then(s => __importStar(require(s))));
418
- if (controller[file.replace(".ts", "")]) {
419
- controller = controller[file.replace(".ts", "")];
420
- }
421
- else if (controller.default) {
422
- controller = controller.default;
423
- }
424
- else {
425
- throw new base_1.InvalidConfigException(BaseChyz.t(`Invalid Controller ${file}`));
426
- }
427
- // This is our instantiated class
428
- const instance = new controller();
429
- BaseChyz.controllers.push(instance);
430
- // The prefix saved to our controller
431
- const prefix = Reflect.getMetadata('prefix', controller);
432
- // Our `routes` array containing all our routes for this controller
433
- const routes = Reflect.getMetadata('routes', controller);
434
- BaseChyz.debug("Controller load ", controller.name, `(${prefix})`);
435
- if (routes) {
436
- routes.forEach(route => {
437
- route.id = (route.path == "/" || route.path == "") ? instance.defaultAction : route.path;
438
- BaseChyz.debug("Controller route Path", prefix + (route.path.startsWith("/") ? route.path : `/${route.path}`));
439
- BaseChyz.propvider[route.requestMethod](prefix + (route.path.startsWith("/") ? route.path : `/${route.path}`), (req, res, next) => this.beforeMiddleware(req, res, next, instance, route), (req, res, next) => this.responseHandler(req, res, next, instance, route), (req, res, next) => this.afterMiddleware(req, res, next, instance, route));
440
- // BaseChyz.propvider[route.requestMethod](prefix + (route.path.startsWith("/") ? route.path : `/${route.path}`),
441
- // async (req: Request, res: Response, next: NextFunction) => {
442
- // try {
443
- // BaseChyz.debug(`Call Request id ${actionId}`)
444
- // http_request_body("Request body " + JSON.stringify(req.body))
445
- // http_request_headers("Request header " + JSON.stringify(req.headers))
446
- // await instance.beforeAction(route, req, res);
447
- // next()
448
- // } catch (e: any) {
449
- //
450
- // BaseChyz.error(e)
451
- // if (e instanceof BaseError) {
452
- // res.status(e?.statusCode || 500)
453
- // res.json(e.toJSON())
454
- // } else {
455
- // res.json(e)
456
- // }
457
- //
458
- // // / next(e)
459
- // }
460
- //
461
- // },
462
- // async (req: Request, res: Response, next: NextFunction) => {
463
- // try {
464
- // // @ts-ignore
465
- // BaseChyz.debug("Request ID ", req.reqId)
466
- // // @ts-ignore
467
- // await instance[route.methodName](req, res, next);
468
- // instance.afterAction(route, req, res);
469
- // } catch (e) {
470
- // BaseChyz.error(e)
471
- // if (e instanceof BaseError) {
472
- // res.status(e.statusCode || 500)
473
- // res.json(e.toJSON())
474
- // } else {
475
- // res.json(e)
476
- // }
477
- // }
478
- // })
479
- });
480
- }
481
- }
482
- });
483
- }
484
- middleware() {
485
- var _a;
486
- BaseChyz.propvider.use(bodyParser.json({ limit: '1mb' }));
487
- BaseChyz.propvider.use(bodyParser.urlencoded({ limit: '1mb', extended: true })); // support encoded bodies
488
- BaseChyz.propvider.use(methodOverride());
489
- BaseChyz.propvider.use(cors());
490
- //
491
- // // CORS
492
- // BaseChyz.express.use(function (req: any, res: Response, next: any) {
493
- // // @ts-ignore
494
- // req.reqId = Utils.uniqueId("chyzzzz_")
495
- // res.setHeader('Content-Type', 'application/json');
496
- // res.setHeader("Access-Control-Allow-Origin", "*");
497
- // res.setHeader("Access-Control-Allow-Credentials", "true");
498
- // res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
499
- // 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");
500
- // next();
501
- // });
502
- //
503
- // compress all responses
504
- const shouldCompress = (req, res) => {
505
- // don't compress responses explicitly asking not
506
- if (req.headers["x-no-compression"] || res.getHeader('Content-Type') === 'text/event-stream') {
507
- return false;
508
- }
509
- // use compression filter function
510
- return compression.filter(req, res);
511
- };
512
- BaseChyz.propvider.use(compression({ filter: shouldCompress }));
513
- //
514
- // //static file path
515
- if (this.config.staticFilePath) {
516
- BaseChyz.info('Static file path', this.config.staticFilePath);
517
- BaseChyz.propvider.use(express_1.default.static(this.config.staticFilePath));
518
- }
519
- //Middlewares
520
- for (const middleware1 of Object.keys(BaseChyz.middlewares)) {
521
- if ((_a = BaseChyz.middlewares[middleware1]) === null || _a === void 0 ? void 0 : _a.keycloak) {
522
- let keycloak = BaseChyz.middlewares[middleware1].keycloak;
523
- //@ts-ignore
524
- BaseChyz.propvider.use(keycloak.middleware(BaseChyz.middlewares[middleware1].config));
525
- }
526
- else {
527
- BaseChyz.propvider.use(BaseChyz.middlewares[middleware1]);
528
- }
529
- }
530
- BaseChyz.propvider.use(this.errorResponder);
531
- BaseChyz.propvider.use(this.errorHandler);
532
- BaseChyz.EventEmitter.emit(base_1.CEvents.ON_MIDDLEWARE, this);
533
- }
534
- Start() {
535
- var _a, _b;
536
- BaseChyz.info("Express Server Starting");
537
- BaseChyz.EventEmitter.emit(base_1.CEvents.ON_BEFORE_START, this);
538
- if ((_a = this.config) === null || _a === void 0 ? void 0 : _a.ssl) {
539
- BaseChyz.httpServer = (0, https_1.createServer)((_b = this.config) === null || _b === void 0 ? void 0 : _b.ssl, BaseChyz.propvider);
540
- BaseChyz.httpServer.listen(this._port, () => {
541
- BaseChyz.info("Express Server Start ");
542
- BaseChyz.info(`Liten Port ${this._port}`);
543
- BaseChyz.info(`https://localhost:${this._port}`);
544
- BaseChyz.info(`https://${ip.address()}:${this._port}`);
545
- BaseChyz.EventEmitter.emit(base_1.CEvents.ON_START, this);
546
- });
547
- }
548
- else {
549
- BaseChyz.httpServer = (0, http_1.createServer)(BaseChyz.propvider);
550
- BaseChyz.propvider.listen(this._port, () => {
551
- BaseChyz.info("Express Server Start ");
552
- BaseChyz.info(`Liten Port ${this._port}`);
553
- BaseChyz.info(`http://localhost:${this._port}`);
554
- BaseChyz.info(`http://${ip.address()}:${this._port}`);
555
- BaseChyz.EventEmitter.emit(base_1.CEvents.ON_START, this);
556
- });
557
- }
558
- return this;
559
- }
560
- }
561
- BaseChyz.propvider = Server;
562
- BaseChyz.date = dayjs;
563
- BaseChyz.logs = new base_1.Logs();
564
- BaseChyz._validate = validate;
565
- BaseChyz.controllers = [];
566
- BaseChyz.components = {};
567
- BaseChyz.middlewares = {};
568
- BaseChyz._EventEmitter = em;
569
- exports.default = BaseChyz;
@@ -1,33 +0,0 @@
1
- /// <reference types="express" />
2
- import { Request, Response } from "../index";
3
- import { CBaseObject } from "./CBaseObject";
4
- export declare class ActionFilter extends CBaseObject {
5
- only: any;
6
- /**
7
- * @var array list of action IDs that this filter should not apply to.
8
- * @see only
9
- */
10
- except: never[];
11
- init(): void;
12
- /**
13
- *
14
- * @param route
15
- * @param req
16
- * @param res
17
- */
18
- beforeFilter(route: any, req: Request, res: Response): Promise<void>;
19
- /**
20
- * This method is invoked right before an action is to be executed (after all possible filters.)
21
- * You may override this method to do last-minute preparation for the action.
22
- * @param Action $action the action to be executed.
23
- * @return bool whether the action should continue to be executed.
24
- */
25
- beforeAction(route: any, req: Request, res: Response): Promise<boolean>;
26
- /**
27
- *
28
- * @param action
29
- * @protected
30
- */
31
- protected isActive(action: any): boolean;
32
- }
33
- //# sourceMappingURL=ActionFilter.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ActionFilter.d.ts","sourceRoot":"","sources":["../../src/base/ActionFilter.ts"],"names":[],"mappings":";AAMA,OAAO,EAAC,OAAO,EAAE,QAAQ,EAAC,MAAM,UAAU,CAAC;AAE3C,OAAO,EAAC,WAAW,EAAC,MAAM,eAAe,CAAA;AAGzC,qBAAa,YAAa,SAAQ,WAAW;IAElC,IAAI,EAAE,GAAG,CAAC;IAEjB;;;OAGG;IACI,MAAM,UAAM;IAGZ,IAAI;IAIX;;;;;OAKG;IACU,YAAY,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ;IAUjE;;;;;OAKG;IACU,YAAY,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ;IAIjE;;;;OAIG;IACH,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,GAAG;CA8BjC"}
@@ -1,90 +0,0 @@
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
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.ActionFilter = void 0;
16
- const Utils_1 = require("../requiments/Utils");
17
- const CBaseObject_1 = require("./CBaseObject");
18
- const BaseChyz_1 = __importDefault(require("../BaseChyz"));
19
- class ActionFilter extends CBaseObject_1.CBaseObject {
20
- constructor() {
21
- super(...arguments);
22
- /**
23
- * @var array list of action IDs that this filter should not apply to.
24
- * @see only
25
- */
26
- this.except = [];
27
- }
28
- init() {
29
- }
30
- /**
31
- *
32
- * @param route
33
- * @param req
34
- * @param res
35
- */
36
- beforeFilter(route, req, res) {
37
- return __awaiter(this, void 0, void 0, function* () {
38
- BaseChyz_1.default.debug("Controller->beforeFilter ", route);
39
- if (!this.isActive(route)) {
40
- return;
41
- }
42
- yield this.beforeAction(route, req, res);
43
- });
44
- }
45
- /**
46
- * This method is invoked right before an action is to be executed (after all possible filters.)
47
- * You may override this method to do last-minute preparation for the action.
48
- * @param Action $action the action to be executed.
49
- * @return bool whether the action should continue to be executed.
50
- */
51
- beforeAction(route, req, res) {
52
- return __awaiter(this, void 0, void 0, function* () {
53
- return true;
54
- });
55
- }
56
- /**
57
- *
58
- * @param action
59
- * @protected
60
- */
61
- isActive(action) {
62
- let id = action.id;
63
- let onlyMatch = false;
64
- let exceptMatch = false;
65
- if (Utils_1.Utils.isEmpty(this.only)) {
66
- onlyMatch = true;
67
- }
68
- else {
69
- onlyMatch = false;
70
- for (const onlyKey of this.only) {
71
- if (Utils_1.Utils.matchWildcard(action.id, onlyKey)) {
72
- onlyMatch = true;
73
- break;
74
- }
75
- }
76
- }
77
- for (const exceptKey in this.except) {
78
- let pattern = this.except[exceptKey];
79
- let reg = new RegExp(`${pattern}$`, "g");
80
- let match = id.match(reg);
81
- // let match = id.startsWith(pattern);
82
- console.log(id, pattern, match, this.except);
83
- if (match && match.length > 0) {
84
- exceptMatch = true;
85
- }
86
- }
87
- return !exceptMatch && onlyMatch;
88
- }
89
- }
90
- exports.ActionFilter = ActionFilter;