chyz 2.0.0-rc.29 → 2.0.0-rc.30

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