namirasoft-node 1.0.12 → 1.0.14

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.
@@ -2,14 +2,29 @@ import * as express from 'express';
2
2
  import { BaseDatabase } from './BaseDatabase';
3
3
  import { SchemaLike } from 'joi';
4
4
  import { AnomalyDetector } from './AnomalyDetector';
5
+ import { ILogger } from 'namirasoft-log';
6
+ import { Meta } from './Meta';
5
7
  export declare abstract class BaseController<D extends BaseDatabase, State, Props> {
6
- showLogAtTheBeginning: boolean;
7
- showLogAtTheEnd: boolean;
8
+ protected showLogAtTheBeginning: boolean;
9
+ protected showLogAtTheEnd: boolean;
10
+ protected req: express.Request;
11
+ protected res: express.Response;
12
+ protected logger: ILogger;
13
+ protected meta: Meta;
14
+ protected result: {};
15
+ protected database: D;
16
+ protected state: State;
17
+ protected props: Props;
18
+ constructor(req: express.Request, res: express.Response);
19
+ abstract getLogger(): ILogger;
20
+ abstract getDatabase(): Promise<D>;
8
21
  abstract getAnomaly(): AnomalyDetector | null;
9
22
  abstract getBodySchema(): SchemaLike | null;
10
23
  abstract getQuerySchema(): SchemaLike | null;
11
- abstract getState(): State;
12
- abstract preHandle(req: express.Request, res: express.Response, database: D, props: Props): Promise<void>;
13
- abstract handle(req: express.Request, res: express.Response, database: D, props: Props): Promise<any>;
14
- abstract postHandle(req: express.Request, res: express.Response, database: D, props: Props): Promise<void>;
24
+ abstract getState(): Promise<State>;
25
+ abstract getProps(): Promise<Props>;
26
+ abstract preHandle(): Promise<void>;
27
+ abstract handle(): Promise<any>;
28
+ abstract postHandle(): Promise<void>;
29
+ run(): Promise<express.Response<any, Record<string, any>>>;
15
30
  }
@@ -1,10 +1,107 @@
1
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
+ };
2
14
  Object.defineProperty(exports, "__esModule", { value: true });
3
15
  exports.BaseController = void 0;
16
+ const Meta_1 = require("./Meta");
17
+ const joi_1 = __importDefault(require("joi"));
18
+ const namirasoft_core_1 = require("namirasoft-core");
4
19
  class BaseController {
5
- constructor() {
20
+ constructor(req, res) {
6
21
  this.showLogAtTheBeginning = false;
7
22
  this.showLogAtTheEnd = true;
23
+ this.req = req;
24
+ this.res = res;
25
+ this.logger = this.getLogger();
26
+ }
27
+ run() {
28
+ return __awaiter(this, void 0, void 0, function* () {
29
+ this.meta = new Meta_1.Meta(this.req);
30
+ // result
31
+ this.result = {};
32
+ try {
33
+ // meta
34
+ this.meta.onStart();
35
+ if (this.showLogAtTheBeginning)
36
+ this.logger.info(JSON.stringify(this.meta));
37
+ // init controller
38
+ this.database = yield this.getDatabase();
39
+ this.state = yield this.getState();
40
+ this.props = yield this.getProps();
41
+ // preHandle
42
+ yield this.preHandle();
43
+ // check for anomaly
44
+ let anomaly = this.getAnomaly();
45
+ if (anomaly != null)
46
+ if (anomaly.isAnomaly(this.meta.ip, this.meta.url))
47
+ namirasoft_core_1.ErrorOperation.throwHTTP(403, 'Suspicious activity detected.');
48
+ // check body validation
49
+ let bodySchema = this.getBodySchema();
50
+ if (bodySchema != null) {
51
+ const validation = yield joi_1.default.compile(bodySchema)
52
+ .prefs({ errors: { label: 'key' } })
53
+ .validate(this.req.body);
54
+ if (validation.error) {
55
+ let message = validation.error.details.map((details) => details.message).join(', ');
56
+ namirasoft_core_1.ErrorOperation.throwHTTP(400, message);
57
+ }
58
+ }
59
+ // check query validation
60
+ let querySchema = this.getQuerySchema();
61
+ if (querySchema != null) {
62
+ const validation = yield joi_1.default.compile(querySchema)
63
+ .prefs({ errors: { label: 'key' } })
64
+ .validate(this.req.query);
65
+ if (validation.error) {
66
+ let message = validation.error.details.map((details) => details.message).join(', ');
67
+ namirasoft_core_1.ErrorOperation.throwHTTP(400, message);
68
+ }
69
+ }
70
+ // call controller
71
+ this.result = yield this.handle();
72
+ if (this.result == null)
73
+ this.result = "Success";
74
+ // postHandle
75
+ yield this.postHandle();
76
+ }
77
+ catch (error) {
78
+ let message;
79
+ if (error instanceof Error) {
80
+ this.meta.error = error;
81
+ message = error.message;
82
+ }
83
+ else
84
+ message = error + "";
85
+ if (error instanceof namirasoft_core_1.HTTPError) {
86
+ this.meta.code = error.code;
87
+ this.logger.error(error.message + "\n" + JSON.stringify(this.meta), undefined, error.stack);
88
+ }
89
+ else {
90
+ this.meta.code = 500;
91
+ if (error instanceof Error)
92
+ this.logger.critical(error.message + "\n" + JSON.stringify(this.meta), undefined, error.stack);
93
+ }
94
+ this.meta.message = message;
95
+ if (error instanceof namirasoft_core_1.HTTPError)
96
+ this.result = this.meta.message;
97
+ else
98
+ this.result = "Sorry, internl server error.";
99
+ }
100
+ this.meta.onFinish();
101
+ if (this.showLogAtTheEnd)
102
+ this.logger.info(JSON.stringify(this.meta));
103
+ return this.res.status(this.meta.code).send(this.result);
104
+ });
8
105
  }
9
106
  }
10
107
  exports.BaseController = BaseController;
@@ -1 +1 @@
1
- {"version":3,"file":"BaseController.js","sourceRoot":"","sources":["../src/BaseController.ts"],"names":[],"mappings":";;;AAIA,MAAsB,cAAc;IAApC;QAEI,0BAAqB,GAAY,KAAK,CAAC;QACvC,oBAAe,GAAY,IAAI,CAAC;IAQpC,CAAC;CAAA;AAXD,wCAWC"}
1
+ {"version":3,"file":"BaseController.js","sourceRoot":"","sources":["../src/BaseController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,iCAA8B;AAC9B,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C;YACrB,IAAI,IAAI,CAAC,eAAe;gBACpB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;YAChD,OAAO,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC7D,CAAC;KAAA;CACJ;AAzHD,wCAyHC"}
package/dist/index.d.ts CHANGED
@@ -2,7 +2,6 @@ export * from "./AnomalyDetector";
2
2
  export * from "./BaseApplication";
3
3
  export * from "./BaseController";
4
4
  export * from "./BaseDatabase";
5
- export * from "./BaseMiddleware";
6
5
  export * from "./BaseSequelizeModel";
7
6
  export * from "./BaseMySqlDatabase";
8
7
  export * from "./BaseSequelizeTable";
package/dist/index.js CHANGED
@@ -18,7 +18,6 @@ __exportStar(require("./AnomalyDetector"), exports);
18
18
  __exportStar(require("./BaseApplication"), exports);
19
19
  __exportStar(require("./BaseController"), exports);
20
20
  __exportStar(require("./BaseDatabase"), exports);
21
- __exportStar(require("./BaseMiddleware"), exports);
22
21
  __exportStar(require("./BaseSequelizeModel"), exports);
23
22
  __exportStar(require("./BaseMySqlDatabase"), exports);
24
23
  __exportStar(require("./BaseSequelizeTable"), exports);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,oDAAkC;AAClC,oDAAkC;AAClC,mDAAiC;AACjC,iDAA+B;AAC/B,mDAAiC;AACjC,uDAAqC;AACrC,sDAAoC;AACpC,uDAAqC;AACrC,0DAAwC;AACxC,8CAA4B;AAC5B,iDAA+B;AAC/B,+CAA6B;AAC7B,gDAA8B;AAC9B,yDAAuC;AACvC,4DAA0C"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,oDAAkC;AAClC,oDAAkC;AAClC,mDAAiC;AACjC,iDAA+B;AAC/B,uDAAqC;AACrC,sDAAoC;AACpC,uDAAqC;AACrC,0DAAwC;AACxC,8CAA4B;AAC5B,iDAA+B;AAC/B,+CAA6B;AAC7B,gDAA8B;AAC9B,yDAAuC;AACvC,4DAA0C"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "namirasoft-node",
3
3
  "description": "Namira Software Corporation Node NPM Package",
4
- "version": "1.0.12",
4
+ "version": "1.0.14",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "scripts": {},
@@ -2,15 +2,130 @@ import * as express from 'express';
2
2
  import { BaseDatabase } from './BaseDatabase';
3
3
  import { SchemaLike } from 'joi';
4
4
  import { AnomalyDetector } from './AnomalyDetector';
5
+ import { ILogger } from 'namirasoft-log';
6
+ import { Meta } from './Meta';
7
+ import Joi from 'joi';
8
+ import { ErrorOperation, HTTPError } from 'namirasoft-core';
9
+
5
10
  export abstract class BaseController<D extends BaseDatabase, State, Props>
6
11
  {
7
- showLogAtTheBeginning: boolean = false;
8
- showLogAtTheEnd: boolean = true;
12
+ protected showLogAtTheBeginning: boolean = false;
13
+ protected showLogAtTheEnd: boolean = true;
14
+ protected req: express.Request;
15
+ protected res: express.Response;
16
+ protected logger: ILogger;
17
+ protected meta!: Meta;
18
+ protected result!: {};
19
+ protected database!: D;
20
+ protected state!: State;
21
+ protected props!: Props;
22
+ constructor(req: express.Request, res: express.Response)
23
+ {
24
+ this.req = req;
25
+ this.res = res;
26
+ this.logger = this.getLogger();
27
+ }
28
+ abstract getLogger(): ILogger;
29
+ abstract getDatabase(): Promise<D>;
9
30
  abstract getAnomaly(): AnomalyDetector | null;
10
31
  abstract getBodySchema(): SchemaLike | null;
11
32
  abstract getQuerySchema(): SchemaLike | null;
12
- abstract getState(): State;
13
- abstract preHandle(req: express.Request, res: express.Response, database: D, props: Props): Promise<void>;
14
- abstract handle(req: express.Request, res: express.Response, database: D, props: Props): Promise<any>;
15
- abstract postHandle(req: express.Request, res: express.Response, database: D, props: Props): Promise<void>;
33
+ abstract getState(): Promise<State>;
34
+ abstract getProps(): Promise<Props>;
35
+ abstract preHandle(): Promise<void>;
36
+ abstract handle(): Promise<any>;
37
+ abstract postHandle(): Promise<void>;
38
+
39
+ async run()
40
+ {
41
+ this.meta = new Meta(this.req);
42
+ // result
43
+ this.result = {};
44
+ try
45
+ {
46
+ // meta
47
+ this.meta.onStart();
48
+ if (this.showLogAtTheBeginning)
49
+ this.logger.info(JSON.stringify(this.meta));
50
+ // init controller
51
+ this.database = await this.getDatabase();
52
+ this.state = await this.getState();
53
+ this.props = await this.getProps();
54
+
55
+ // preHandle
56
+ await this.preHandle();
57
+
58
+ // check for anomaly
59
+ let anomaly: AnomalyDetector | null = this.getAnomaly();
60
+ if (anomaly != null)
61
+ if (anomaly.isAnomaly(this.meta.ip, this.meta.url))
62
+ ErrorOperation.throwHTTP(403, 'Suspicious activity detected.');
63
+
64
+ // check body validation
65
+ let bodySchema = this.getBodySchema();
66
+ if (bodySchema != null)
67
+ {
68
+ const validation = await Joi.compile(bodySchema)
69
+ .prefs({ errors: { label: 'key' } })
70
+ .validate(this.req.body);
71
+ if (validation.error)
72
+ {
73
+ let message = validation.error.details.map((details) => details.message).join(', ');
74
+ ErrorOperation.throwHTTP(400, message);
75
+ }
76
+ }
77
+ // check query validation
78
+ let querySchema = this.getQuerySchema();
79
+ if (querySchema != null)
80
+ {
81
+ const validation = await Joi.compile(querySchema)
82
+ .prefs({ errors: { label: 'key' } })
83
+ .validate(this.req.query);
84
+ if (validation.error)
85
+ {
86
+ let message = validation.error.details.map((details) => details.message).join(', ');
87
+ ErrorOperation.throwHTTP(400, message);
88
+ }
89
+ }
90
+
91
+ // call controller
92
+ this.result = await this.handle();
93
+ if (this.result == null)
94
+ this.result = "Success";
95
+
96
+ // postHandle
97
+ await this.postHandle();
98
+ } catch (error)
99
+ {
100
+ let message: string;
101
+ if (error instanceof Error)
102
+ {
103
+ this.meta.error = error;
104
+ message = error.message;
105
+ }
106
+ else
107
+ message = error + "";
108
+
109
+ if (error instanceof HTTPError)
110
+ {
111
+ this.meta.code = error.code;
112
+ this.logger.error(error.message + "\n" + JSON.stringify(this.meta), undefined, error.stack);
113
+ }
114
+ else
115
+ {
116
+ this.meta.code = 500;
117
+ if (error instanceof Error)
118
+ this.logger.critical(error.message + "\n" + JSON.stringify(this.meta), undefined, error.stack);
119
+ }
120
+ this.meta.message = message;
121
+ if (error instanceof HTTPError)
122
+ this.result = this.meta.message;
123
+ else
124
+ this.result = "Sorry, internl server error.";
125
+ }
126
+ this.meta.onFinish();
127
+ if (this.showLogAtTheEnd)
128
+ this.logger.info(JSON.stringify(this.meta));
129
+ return this.res.status(this.meta.code).send(this.result);
130
+ }
16
131
  }
package/src/index.ts CHANGED
@@ -2,7 +2,6 @@ export * from "./AnomalyDetector";
2
2
  export * from "./BaseApplication";
3
3
  export * from "./BaseController";
4
4
  export * from "./BaseDatabase";
5
- export * from "./BaseMiddleware";
6
5
  export * from "./BaseSequelizeModel";
7
6
  export * from "./BaseMySqlDatabase";
8
7
  export * from "./BaseSequelizeTable";
@@ -1,14 +0,0 @@
1
- import * as express from 'express';
2
- import { BaseDatabase } from './BaseDatabase';
3
- import { BaseController } from './BaseController';
4
- import { ILogger } from "namirasoft-log";
5
- export declare abstract class BaseMiddleware<D extends BaseDatabase, State, Props> {
6
- protected logger: ILogger;
7
- abstract getDatabase(): Promise<D>;
8
- abstract getLogger(): ILogger;
9
- abstract preHandle(req: express.Request, res: express.Response, database: D, props: Props): Promise<void>;
10
- abstract postHandle(req: express.Request, res: express.Response, database: D, props: Props): Promise<void>;
11
- abstract getProps(req: express.Request, res: express.Response, database: D, state: State): Promise<Props>;
12
- constructor();
13
- getHandler(controller: BaseController<D, State, Props>): (req: express.Request, res: express.Response) => Promise<express.Response<any, Record<string, any>>>;
14
- }
@@ -1,108 +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.BaseMiddleware = void 0;
16
- const Meta_1 = require("./Meta");
17
- const joi_1 = __importDefault(require("joi"));
18
- const namirasoft_core_1 = require("namirasoft-core");
19
- class BaseMiddleware {
20
- constructor() {
21
- this.logger = this.getLogger();
22
- }
23
- getHandler(controller) {
24
- return (req, res) => __awaiter(this, void 0, void 0, function* () {
25
- // meta
26
- let meta = new Meta_1.Meta(req);
27
- // result
28
- let result = {};
29
- try {
30
- // meta
31
- meta.onStart();
32
- if (controller.showLogAtTheBeginning)
33
- this.logger.info(JSON.stringify(meta));
34
- // init controller
35
- let database = yield this.getDatabase();
36
- let state = controller.getState();
37
- let props = yield this.getProps(req, res, database, state);
38
- // preHandle
39
- yield this.preHandle(req, res, database, props);
40
- yield controller.preHandle(req, res, database, props);
41
- // check for anomaly
42
- let anomaly = controller.getAnomaly();
43
- if (anomaly != null)
44
- if (anomaly.isAnomaly(meta.ip, meta.url))
45
- namirasoft_core_1.ErrorOperation.throwHTTP(403, 'Suspicious activity detected.');
46
- // check body validation
47
- let bodySchema = controller.getBodySchema();
48
- if (bodySchema != null) {
49
- const validation = yield joi_1.default.compile(bodySchema)
50
- .prefs({ errors: { label: 'key' } })
51
- .validate(req.body);
52
- if (validation.error) {
53
- let message = validation.error.details.map((details) => details.message).join(', ');
54
- namirasoft_core_1.ErrorOperation.throwHTTP(400, message);
55
- }
56
- }
57
- // check query validation
58
- let querySchema = controller.getQuerySchema();
59
- if (querySchema != null) {
60
- const validation = yield joi_1.default.compile(querySchema)
61
- .prefs({ errors: { label: 'key' } })
62
- .validate(req.query);
63
- if (validation.error) {
64
- let message = validation.error.details.map((details) => details.message).join(', ');
65
- namirasoft_core_1.ErrorOperation.throwHTTP(400, message);
66
- }
67
- }
68
- // call controller
69
- if (controller.handle)
70
- result = yield controller.handle(req, res, database, props);
71
- if (result == null)
72
- result = "Success";
73
- // postHandle
74
- yield controller.postHandle(req, res, database, props);
75
- yield this.postHandle(req, res, database, props);
76
- }
77
- catch (error) {
78
- let message;
79
- if (error instanceof Error) {
80
- meta.error = error;
81
- message = error.message;
82
- }
83
- else
84
- message = error + "";
85
- if (error instanceof namirasoft_core_1.HTTPError) {
86
- meta.code = error.code;
87
- this.logger.error(error.message + "\n" + JSON.stringify(meta), undefined, error.stack);
88
- }
89
- else {
90
- meta.code = 500;
91
- if (error instanceof Error)
92
- this.logger.critical(error.message + "\n" + JSON.stringify(meta), undefined, error.stack);
93
- }
94
- meta.message = message;
95
- if (error instanceof namirasoft_core_1.HTTPError)
96
- result = meta.message;
97
- else
98
- result = "Sorry, internl server error.";
99
- }
100
- meta.onFinish();
101
- if (controller.showLogAtTheEnd)
102
- this.logger.info(JSON.stringify(meta));
103
- return res.status(meta.code).send(result);
104
- });
105
- }
106
- }
107
- exports.BaseMiddleware = BaseMiddleware;
108
- //# sourceMappingURL=BaseMiddleware.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"BaseMiddleware.js","sourceRoot":"","sources":["../src/BaseMiddleware.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAEA,iCAA8B;AAC9B,8CAAsB;AAGtB,qDAA4D;AAG5D,MAAsB,cAAc;IAQhC;QAEI,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;IAC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CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;YAC3C,OAAO,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC9C,CAAC,CAAA,CAAC;IACN,CAAC;CACJ;AA/GD,wCA+GC"}
@@ -1,121 +0,0 @@
1
- import * as express from 'express';
2
- import { BaseDatabase } from './BaseDatabase';
3
- import { Meta } from './Meta';
4
- import Joi from 'joi';
5
- import { AnomalyDetector } from './AnomalyDetector';
6
- import { BaseController } from './BaseController';
7
- import { ErrorOperation, HTTPError } from 'namirasoft-core';
8
- import { ILogger } from "namirasoft-log";
9
-
10
- export abstract class BaseMiddleware<D extends BaseDatabase, State, Props>
11
- {
12
- protected logger: ILogger;
13
- abstract getDatabase(): Promise<D>;
14
- abstract getLogger(): ILogger;
15
- abstract preHandle(req: express.Request, res: express.Response, database: D, props: Props): Promise<void>;
16
- abstract postHandle(req: express.Request, res: express.Response, database: D, props: Props): Promise<void>;
17
- abstract getProps(req: express.Request, res: express.Response, database: D, state: State): Promise<Props>;
18
- constructor()
19
- {
20
- this.logger = this.getLogger();
21
- }
22
- getHandler(controller: BaseController<D, State, Props>)
23
- {
24
- return async (req: express.Request, res: express.Response) =>
25
- {
26
- // meta
27
- let meta = new Meta(req);
28
- // result
29
- let result = {};
30
- try
31
- {
32
- // meta
33
- meta.onStart();
34
- if (controller.showLogAtTheBeginning)
35
- this.logger.info(JSON.stringify(meta));
36
- // init controller
37
- let database = await this.getDatabase();
38
- let state = controller.getState();
39
- let props = await this.getProps(req, res, database, state);
40
-
41
- // preHandle
42
- await this.preHandle(req, res, database, props);
43
- await controller.preHandle(req, res, database, props);
44
-
45
- // check for anomaly
46
- let anomaly: AnomalyDetector | null = controller.getAnomaly();
47
- if (anomaly != null)
48
- if (anomaly.isAnomaly(meta.ip, meta.url))
49
- ErrorOperation.throwHTTP(403, 'Suspicious activity detected.');
50
-
51
- // check body validation
52
- let bodySchema = controller.getBodySchema();
53
- if (bodySchema != null)
54
- {
55
- const validation = await Joi.compile(bodySchema)
56
- .prefs({ errors: { label: 'key' } })
57
- .validate(req.body);
58
- if (validation.error)
59
- {
60
- let message = validation.error.details.map((details) => details.message).join(', ');
61
- ErrorOperation.throwHTTP(400, message);
62
- }
63
- }
64
- // check query validation
65
- let querySchema = controller.getQuerySchema();
66
- if (querySchema != null)
67
- {
68
- const validation = await Joi.compile(querySchema)
69
- .prefs({ errors: { label: 'key' } })
70
- .validate(req.query);
71
- if (validation.error)
72
- {
73
- let message = validation.error.details.map((details) => details.message).join(', ');
74
- ErrorOperation.throwHTTP(400, message);
75
- }
76
- }
77
-
78
- // call controller
79
- if (controller.handle)
80
- result = await controller.handle(req, res, database, props);
81
- if (result == null)
82
- result = "Success";
83
-
84
- // postHandle
85
- await controller.postHandle(req, res, database, props);
86
- await this.postHandle(req, res, database, props);
87
- } catch (error)
88
- {
89
- let message: string;
90
- if (error instanceof Error)
91
- {
92
- meta.error = error;
93
- message = error.message;
94
- }
95
- else
96
- message = error + "";
97
-
98
- if (error instanceof HTTPError)
99
- {
100
- meta.code = error.code;
101
- this.logger.error(error.message + "\n" + JSON.stringify(meta), undefined, error.stack);
102
- }
103
- else
104
- {
105
- meta.code = 500;
106
- if (error instanceof Error)
107
- this.logger.critical(error.message + "\n" + JSON.stringify(meta), undefined, error.stack);
108
- }
109
- meta.message = message;
110
- if (error instanceof HTTPError)
111
- result = meta.message;
112
- else
113
- result = "Sorry, internl server error.";
114
- }
115
- meta.onFinish();
116
- if (controller.showLogAtTheEnd)
117
- this.logger.info(JSON.stringify(meta));
118
- return res.status(meta.code).send(result);
119
- };
120
- }
121
- }