@estgbue/mezgeb 0.0.1

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 (52) hide show
  1. package/dist/index.d.ts +3 -0
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +17 -0
  4. package/dist/mezgeb/client/client-audit.interceptor.d.ts +18 -0
  5. package/dist/mezgeb/client/client-audit.interceptor.d.ts.map +1 -0
  6. package/dist/mezgeb/client/client-audit.interceptor.js +133 -0
  7. package/dist/mezgeb/client/client.controller.d.ts +1 -0
  8. package/dist/mezgeb/client/client.controller.d.ts.map +1 -0
  9. package/dist/mezgeb/client/client.controller.js +1 -0
  10. package/dist/mezgeb/client/client.logger.config.d.ts +2 -0
  11. package/dist/mezgeb/client/client.logger.config.d.ts.map +1 -0
  12. package/dist/mezgeb/client/client.logger.config.js +25 -0
  13. package/dist/mezgeb/client/client.module.d.ts +3 -0
  14. package/dist/mezgeb/client/client.module.d.ts.map +1 -0
  15. package/dist/mezgeb/client/client.module.js +30 -0
  16. package/dist/mezgeb/client/client.subscriber.d.ts +10 -0
  17. package/dist/mezgeb/client/client.subscriber.d.ts.map +1 -0
  18. package/dist/mezgeb/client/client.subscriber.js +61 -0
  19. package/dist/mezgeb/client/event-audit.decorator.d.ts +3 -0
  20. package/dist/mezgeb/client/event-audit.decorator.d.ts.map +1 -0
  21. package/dist/mezgeb/client/event-audit.decorator.js +7 -0
  22. package/dist/mezgeb/client/ignore-logger.decorator.d.ts +3 -0
  23. package/dist/mezgeb/client/ignore-logger.decorator.d.ts.map +1 -0
  24. package/dist/mezgeb/client/ignore-logger.decorator.js +7 -0
  25. package/dist/mezgeb/mezgeb.dto.d.ts +46 -0
  26. package/dist/mezgeb/mezgeb.dto.d.ts.map +1 -0
  27. package/dist/mezgeb/mezgeb.dto.js +18 -0
  28. package/dist/mezgeb/mezgeb.enum.d.ts +20 -0
  29. package/dist/mezgeb/mezgeb.enum.d.ts.map +1 -0
  30. package/dist/mezgeb/mezgeb.enum.js +23 -0
  31. package/dist/mezgeb/mezgeb.type.d.ts +17 -0
  32. package/dist/mezgeb/mezgeb.type.d.ts.map +1 -0
  33. package/dist/mezgeb/mezgeb.type.js +2 -0
  34. package/dist/mezgeb.module.d.ts +3 -0
  35. package/dist/mezgeb.module.d.ts.map +1 -0
  36. package/dist/mezgeb.module.js +23 -0
  37. package/libs/mezgeb/src/index.ts +2 -0
  38. package/libs/mezgeb/src/mezgeb/client/client-audit.interceptor.ts +176 -0
  39. package/libs/mezgeb/src/mezgeb/client/client.controller.ts +0 -0
  40. package/libs/mezgeb/src/mezgeb/client/client.logger.config.ts +24 -0
  41. package/libs/mezgeb/src/mezgeb/client/client.module.ts +18 -0
  42. package/libs/mezgeb/src/mezgeb/client/client.subscriber.ts +60 -0
  43. package/libs/mezgeb/src/mezgeb/client/event-audit.decorator.ts +4 -0
  44. package/libs/mezgeb/src/mezgeb/client/ignore-logger.decorator.ts +4 -0
  45. package/libs/mezgeb/src/mezgeb/mezgeb.dto.ts +50 -0
  46. package/libs/mezgeb/src/mezgeb/mezgeb.enum.ts +21 -0
  47. package/libs/mezgeb/src/mezgeb/mezgeb.type.ts +17 -0
  48. package/libs/mezgeb/src/mezgeb.module.ts +11 -0
  49. package/libs/mezgeb/tsconfig.lib.json +9 -0
  50. package/nest-cli.json +16 -0
  51. package/package.json +16 -0
  52. package/tsconfig.json +105 -0
@@ -0,0 +1,3 @@
1
+ export * from './mezgeb/client/client.module';
2
+ export * from './mezgeb.module';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../libs/mezgeb/src/index.ts"],"names":[],"mappings":"AAAA,cAAc,+BAA+B,CAAC;AAC9C,cAAc,iBAAiB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./mezgeb.module"), exports);
@@ -0,0 +1,18 @@
1
+ import { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';
2
+ import { Reflector } from '@nestjs/core';
3
+ import { Observable } from 'rxjs';
4
+ import { ClientProxy } from '@nestjs/microservices';
5
+ import { DataSource } from 'typeorm';
6
+ export declare class ClientLoggerInterceptor implements NestInterceptor {
7
+ private reflector;
8
+ private readonly connection;
9
+ private readonly rmsRMQClient;
10
+ constructor(reflector: Reflector, connection: DataSource, rmsRMQClient: ClientProxy);
11
+ intercept(context: ExecutionContext, next: CallHandler): Observable<any>;
12
+ private handleRequestAuditInitiation;
13
+ private handleEventAuditInitiation;
14
+ private handleTransaction;
15
+ private mapHeaders;
16
+ private mapCookies;
17
+ }
18
+ //# sourceMappingURL=client-audit.interceptor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-audit.interceptor.d.ts","sourceRoot":"","sources":["../../../libs/mezgeb/src/mezgeb/client/client-audit.interceptor.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,gBAAgB,EAGhB,eAAe,EAChB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAA6B,UAAU,EAAE,MAAM,MAAM,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAOrC,qBACa,uBAAwB,YAAW,eAAe;IAE3D,OAAO,CAAC,SAAS;IACjB,OAAO,CAAC,QAAQ,CAAC,UAAU;IAE3B,OAAO,CAAC,QAAQ,CAAC,YAAY;gBAHrB,SAAS,EAAE,SAAS,EACX,UAAU,EAAE,UAAU,EAEtB,YAAY,EAAE,WAAW;IAG5C,SAAS,CAAC,OAAO,EAAE,gBAAgB,EAAE,IAAI,EAAE,WAAW,GAAG,UAAU,CAAC,GAAG,CAAC;IAoDxE,OAAO,CAAC,4BAA4B;IAiCpC,OAAO,CAAC,0BAA0B;IA2BlC,OAAO,CAAC,iBAAiB;IAsBzB,OAAO,CAAC,UAAU;IAQlB,OAAO,CAAC,UAAU;CAOnB"}
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.ClientLoggerInterceptor = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const core_1 = require("@nestjs/core");
18
+ const rxjs_1 = require("rxjs");
19
+ const microservices_1 = require("@nestjs/microservices");
20
+ const typeorm_1 = require("typeorm");
21
+ const crypto_1 = require("crypto");
22
+ const event_audit_decorator_1 = require("./event-audit.decorator");
23
+ const ignore_logger_decorator_1 = require("./ignore-logger.decorator");
24
+ const mezgeb_enum_1 = require("../mezgeb.enum");
25
+ let ClientLoggerInterceptor = class ClientLoggerInterceptor {
26
+ constructor(reflector, connection, rmsRMQClient) {
27
+ this.reflector = reflector;
28
+ this.connection = connection;
29
+ this.rmsRMQClient = rmsRMQClient;
30
+ }
31
+ intercept(context, next) {
32
+ const auditRmqEvent = this.reflector.getAllAndOverride(event_audit_decorator_1.AUDIT_RMQ_EVENT, [context.getHandler(), context.getClass()]);
33
+ const isAuditIgnored = this.reflector.getAllAndOverride(ignore_logger_decorator_1.IGNORE_AUDIT_LOGGER, [context.getHandler(), context.getClass()]);
34
+ if (isAuditIgnored)
35
+ return next.handle();
36
+ if (!auditRmqEvent &&
37
+ context.switchToHttp().getRequest().method == mezgeb_enum_1.EAuditLogRequestMethod.GET)
38
+ return next.handle();
39
+ const ds = this.connection;
40
+ const requestId = (ds.requestId = (0, crypto_1.randomUUID)());
41
+ const startTime = Date.now();
42
+ if (auditRmqEvent)
43
+ this.handleEventAuditInitiation(context, next, requestId);
44
+ else
45
+ this.handleRequestAuditInitiation(context, next, requestId);
46
+ return next.handle().pipe((0, rxjs_1.map)((resp) => {
47
+ const { statusCode } = context.switchToHttp().getResponse();
48
+ this.handleTransaction('Commit', statusCode, requestId, startTime);
49
+ return resp;
50
+ }), (0, rxjs_1.catchError)((error) => {
51
+ var _a;
52
+ const statusCode = (_a = error.status) !== null && _a !== void 0 ? _a : error.code;
53
+ this.handleTransaction('Rollback', statusCode, requestId, startTime, error === null || error === void 0 ? void 0 : error.message);
54
+ throw error;
55
+ }), (0, rxjs_1.finalize)(() => {
56
+ const ds = this.connection;
57
+ ds.user = null;
58
+ ds.requestId = null;
59
+ }));
60
+ }
61
+ handleRequestAuditInitiation(context, next, requestId) {
62
+ var _a, _b;
63
+ const req = context.switchToHttp().getRequest();
64
+ const { ip, ips, method, originalUrl, headers, body, params, user } = req;
65
+ const ds = this.connection;
66
+ const userPayload = (ds.user = {
67
+ id: user === null || user === void 0 ? void 0 : user.id,
68
+ name: `${user === null || user === void 0 ? void 0 : user.firstName} ${user === null || user === void 0 ? void 0 : user.lastName}`,
69
+ organizationId: (_a = user === null || user === void 0 ? void 0 : user.organization) === null || _a === void 0 ? void 0 : _a.id,
70
+ organizationName: (_b = user === null || user === void 0 ? void 0 : user.organization) === null || _b === void 0 ? void 0 : _b.name,
71
+ });
72
+ const log = {
73
+ id: requestId,
74
+ requestMethod: method,
75
+ application: process.env.APPLICATION_NAME,
76
+ module: originalUrl.split('/')[2],
77
+ requestBody: originalUrl.includes('/auth') ? {} : body,
78
+ requestHeader: this.mapHeaders(headers),
79
+ statusCode: 201,
80
+ ipAddress: (ips === null || ips === void 0 ? void 0 : ips.length) ? ips[0] : ip,
81
+ executionTime: 0,
82
+ user: userPayload,
83
+ };
84
+ this.rmsRMQClient.emit(mezgeb_enum_1.RegisterRequestAudit, log);
85
+ }
86
+ handleEventAuditInitiation(context, next, requestId) {
87
+ const eventPayload = context.getArgs()[0];
88
+ const eventPattern = context.getArgs()[1].args[2];
89
+ const ds = this.connection;
90
+ const userPayload = (ds.user = {});
91
+ const log = {
92
+ id: requestId,
93
+ requestMethod: mezgeb_enum_1.EAuditLogRequestMethod.EVENT,
94
+ application: process.env.APPLICATION_NAME,
95
+ module: eventPattern,
96
+ requestBody: eventPayload,
97
+ requestHeader: {},
98
+ statusCode: 201,
99
+ ipAddress: '-',
100
+ executionTime: 0,
101
+ user: userPayload,
102
+ };
103
+ this.rmsRMQClient.emit(mezgeb_enum_1.RegisterRequestAudit, log);
104
+ }
105
+ handleTransaction(type, statusCode, requestId, startTime, remark) {
106
+ const executionTime = Date.now() - startTime;
107
+ const approvePayload = {
108
+ requestId,
109
+ executionTime,
110
+ statusCode,
111
+ remark,
112
+ };
113
+ this.rmsRMQClient.emit(type == 'Commit' ? mezgeb_enum_1.CommitRequestAudit : mezgeb_enum_1.RollbackRequestAudit, approvePayload);
114
+ }
115
+ mapHeaders(headers) {
116
+ return Object.assign(Object.assign({}, headers), { authorization: (headers === null || headers === void 0 ? void 0 : headers.authorization) ? 'Bearer [REDACTED]' : undefined, cookie: (headers === null || headers === void 0 ? void 0 : headers.cookie) ? this.mapCookies(headers.cookie) : undefined });
117
+ }
118
+ mapCookies(cookie) {
119
+ return cookie.split(';').reduce((acc, c) => {
120
+ const [key] = c.split('=').map((part) => part.trim());
121
+ acc.push(key);
122
+ return acc;
123
+ }, []);
124
+ }
125
+ };
126
+ exports.ClientLoggerInterceptor = ClientLoggerInterceptor;
127
+ exports.ClientLoggerInterceptor = ClientLoggerInterceptor = __decorate([
128
+ (0, common_1.Injectable)(),
129
+ __param(2, (0, common_1.Inject)(ClientLoggerInterceptor)),
130
+ __metadata("design:paramtypes", [core_1.Reflector,
131
+ typeorm_1.DataSource,
132
+ microservices_1.ClientProxy])
133
+ ], ClientLoggerInterceptor);
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=client.controller.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.controller.d.ts","sourceRoot":"","sources":["../../../libs/mezgeb/src/mezgeb/client/client.controller.ts"],"names":[],"mappings":""}
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,2 @@
1
+ export declare const auditLoggerConfig: any;
2
+ //# sourceMappingURL=client.logger.config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.logger.config.d.ts","sourceRoot":"","sources":["../../../libs/mezgeb/src/mezgeb/client/client.logger.config.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,iBAAiB,EAAE,GAmB/B,CAAC"}
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.auditLoggerConfig = void 0;
4
+ const microservices_1 = require("@nestjs/microservices");
5
+ const mezgeb_enum_1 = require("../mezgeb.enum");
6
+ exports.auditLoggerConfig = {
7
+ name: mezgeb_enum_1.ClientLoggerInterceptor,
8
+ transport: microservices_1.Transport.RMQ,
9
+ options: {
10
+ urls: [process.env.RMQ_URL],
11
+ queue: mezgeb_enum_1.AuditLoggerRMQQueue,
12
+ prefetchCount: 1,
13
+ noAck: false,
14
+ isGlobalPrefetchCount: true,
15
+ socketOptions: {
16
+ frameMax: 16384,
17
+ heartbeat: 60,
18
+ },
19
+ queueOptions: {
20
+ durable: true,
21
+ deadLetterExchange: mezgeb_enum_1.AuditDeadLetterExchange,
22
+ deadLetterRoutingKey: mezgeb_enum_1.DeadAuditRoutingKey,
23
+ },
24
+ },
25
+ };
@@ -0,0 +1,3 @@
1
+ export declare class AuditClientModule {
2
+ }
3
+ //# sourceMappingURL=client.module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.module.d.ts","sourceRoot":"","sources":["../../../libs/mezgeb/src/mezgeb/client/client.module.ts"],"names":[],"mappings":"AAOA,qBAUa,iBAAiB;CAAG"}
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.ClientModule = void 0;
10
+ const common_1 = require("@nestjs/common");
11
+ const core_1 = require("@nestjs/core");
12
+ const microservices_1 = require("@nestjs/microservices");
13
+ const client_logger_config_1 = require("./client.logger.config");
14
+ const client_audit_interceptor_1 = require("./client-audit.interceptor");
15
+ const client_subscriber_1 = require("./client.subscriber");
16
+ let ClientModule = class ClientModule {
17
+ };
18
+ exports.ClientModule = ClientModule;
19
+ exports.ClientModule = ClientModule = __decorate([
20
+ (0, common_1.Module)({
21
+ imports: [microservices_1.ClientsModule.register([client_logger_config_1.auditLoggerConfig])],
22
+ providers: [
23
+ {
24
+ provide: core_1.APP_INTERCEPTOR,
25
+ useClass: client_audit_interceptor_1.ClientLoggerInterceptor,
26
+ },
27
+ client_subscriber_1.ClientSubscriber,
28
+ ],
29
+ })
30
+ ], ClientModule);
@@ -0,0 +1,10 @@
1
+ import { ClientProxy } from '@nestjs/microservices';
2
+ import { AfterQueryEvent, DataSource, EntitySubscriberInterface, InsertEvent } from 'typeorm';
3
+ export declare class ClientSubscriber implements EntitySubscriberInterface {
4
+ private readonly dataSource;
5
+ private readonly rmsRMQClient;
6
+ constructor(dataSource: DataSource, rmsRMQClient: ClientProxy);
7
+ afterInsert(event: InsertEvent<any>): Promise<any> | void;
8
+ afterQuery(event: AfterQueryEvent<any>): Promise<any> | void;
9
+ }
10
+ //# sourceMappingURL=client.subscriber.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.subscriber.d.ts","sourceRoot":"","sources":["../../../libs/mezgeb/src/mezgeb/client/client.subscriber.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EACL,eAAe,EACf,UAAU,EACV,yBAAyB,EAEzB,WAAW,EACZ,MAAM,SAAS,CAAC;AAKjB,qBACa,gBAAiB,YAAW,yBAAyB;IAE9D,OAAO,CAAC,QAAQ,CAAC,UAAU;IAE3B,OAAO,CAAC,QAAQ,CAAC,YAAY;gBAFZ,UAAU,EAAE,UAAU,EAEtB,YAAY,EAAE,WAAW;IAK5C,WAAW,CAAC,KAAK,EAAE,WAAW,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI;IAczD,UAAU,CAAC,KAAK,EAAE,eAAe,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI;CAsB7D"}
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.ClientSubscriber = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const microservices_1 = require("@nestjs/microservices");
18
+ const typeorm_1 = require("typeorm");
19
+ const mezgeb_enum_1 = require("../mezgeb.enum");
20
+ let ClientSubscriber = class ClientSubscriber {
21
+ constructor(dataSource, rmsRMQClient) {
22
+ this.dataSource = dataSource;
23
+ this.rmsRMQClient = rmsRMQClient;
24
+ dataSource.subscribers.push(this);
25
+ }
26
+ afterInsert(event) {
27
+ const ds = this.dataSource;
28
+ const payload = {
29
+ user: ds.user,
30
+ entityName: event.metadata.tableName,
31
+ entityId: event.entity.id,
32
+ entity: event.entity,
33
+ requestId: ds.requestId,
34
+ query: 'INSERT',
35
+ createdAt: new Date(),
36
+ };
37
+ this.rmsRMQClient.emit(mezgeb_enum_1.RecordInsertion, payload);
38
+ }
39
+ afterQuery(event) {
40
+ if (!event.success ||
41
+ !(event.query.startsWith('DELETE') || event.query.startsWith('UPDATE'))) {
42
+ return;
43
+ }
44
+ const ds = this.dataSource;
45
+ const payload = {
46
+ createdAt: new Date(),
47
+ query: event.query,
48
+ requestId: ds.requestId,
49
+ parameters: event.parameters,
50
+ user: ds.user,
51
+ };
52
+ this.rmsRMQClient.emit(event.query.startsWith('DELETE') ? mezgeb_enum_1.RecordDeletion : mezgeb_enum_1.RecordUpdate, payload);
53
+ }
54
+ };
55
+ exports.ClientSubscriber = ClientSubscriber;
56
+ exports.ClientSubscriber = ClientSubscriber = __decorate([
57
+ (0, typeorm_1.EventSubscriber)(),
58
+ __param(1, (0, common_1.Inject)(mezgeb_enum_1.ClientLoggerInterceptor)),
59
+ __metadata("design:paramtypes", [typeorm_1.DataSource,
60
+ microservices_1.ClientProxy])
61
+ ], ClientSubscriber);
@@ -0,0 +1,3 @@
1
+ export declare const AUDIT_RMQ_EVENT = "AuditRmqEvent";
2
+ export declare const AuditRmqEvent: () => import("@nestjs/common").CustomDecorator<string>;
3
+ //# sourceMappingURL=event-audit.decorator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-audit.decorator.d.ts","sourceRoot":"","sources":["../../../libs/mezgeb/src/mezgeb/client/event-audit.decorator.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe,kBAAkB,CAAC;AAC/C,eAAO,MAAM,aAAa,wDAA2C,CAAC"}
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuditRmqEvent = exports.AUDIT_RMQ_EVENT = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ exports.AUDIT_RMQ_EVENT = 'AuditRmqEvent';
6
+ const AuditRmqEvent = () => (0, common_1.SetMetadata)(exports.AUDIT_RMQ_EVENT, true);
7
+ exports.AuditRmqEvent = AuditRmqEvent;
@@ -0,0 +1,3 @@
1
+ export declare const IGNORE_AUDIT_LOGGER = "ignoreAuditLogger";
2
+ export declare const IgnoreLoggerAudit: () => import("@nestjs/common").CustomDecorator<string>;
3
+ //# sourceMappingURL=ignore-logger.decorator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ignore-logger.decorator.d.ts","sourceRoot":"","sources":["../../../libs/mezgeb/src/mezgeb/client/ignore-logger.decorator.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,mBAAmB,sBAAsB,CAAC;AACvD,eAAO,MAAM,iBAAiB,wDAA+C,CAAC"}
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IgnoreLoggerAudit = exports.IGNORE_AUDIT_LOGGER = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ exports.IGNORE_AUDIT_LOGGER = 'ignoreAuditLogger';
6
+ const IgnoreLoggerAudit = () => (0, common_1.SetMetadata)(exports.IGNORE_AUDIT_LOGGER, true);
7
+ exports.IgnoreLoggerAudit = IgnoreLoggerAudit;
@@ -0,0 +1,46 @@
1
+ import { EAuditLogRequestMethod } from "./mezgeb.enum";
2
+ export declare class CreateAuditLogDto {
3
+ requestMethod: EAuditLogRequestMethod;
4
+ id: string;
5
+ application: string;
6
+ module: string;
7
+ requestBody: any;
8
+ requestHeader: any;
9
+ statusCode: number;
10
+ ipAddress: string;
11
+ executionTime: number;
12
+ user: any;
13
+ }
14
+ export declare class UpdateEventDTO {
15
+ entityId?: string;
16
+ entityName: string;
17
+ user: any;
18
+ requestId: string;
19
+ whereParams?: Record<string, any>;
20
+ setParams?: Record<string, any>;
21
+ createdAt: Date;
22
+ }
23
+ export declare class CreateEventDTO {
24
+ entity: any;
25
+ entityId?: string;
26
+ entityName: string;
27
+ user: any;
28
+ requestId: string;
29
+ createdAt: Date;
30
+ query?: string;
31
+ parameters?: any[];
32
+ }
33
+ export declare class EmitQueryDTO {
34
+ createdAt: Date;
35
+ query: string;
36
+ parameters?: any[];
37
+ requestId: string;
38
+ user?: any;
39
+ }
40
+ export declare class ApproveTransactionPayload {
41
+ requestId: string;
42
+ executionTime: number;
43
+ statusCode: number;
44
+ remark?: string;
45
+ }
46
+ //# sourceMappingURL=mezgeb.dto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mezgeb.dto.d.ts","sourceRoot":"","sources":["../../libs/mezgeb/src/mezgeb/mezgeb.dto.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAEvD,qBAAa,iBAAiB;IAC5B,aAAa,EAAG,sBAAsB,CAAC;IACvC,EAAE,EAAG,MAAM,CAAC;IACZ,WAAW,EAAG,MAAM,CAAC;IACrB,MAAM,EAAG,MAAM,CAAC;IAChB,WAAW,EAAG,GAAG,CAAC;IAClB,aAAa,EAAG,GAAG,CAAC;IACpB,UAAU,EAAG,MAAM,CAAC;IACpB,SAAS,EAAG,MAAM,CAAC;IACnB,aAAa,EAAG,MAAM,CAAC;IACvB,IAAI,EAAG,GAAG,CAAC;CACZ;AAED,qBAAa,cAAc;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,EAAG,MAAM,CAAC;IACpB,IAAI,EAAE,GAAG,CAAC;IACV,SAAS,EAAG,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAClC,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAChC,SAAS,EAAG,IAAI,CAAC;CAClB;AAED,qBAAa,cAAc;IACzB,MAAM,EAAE,GAAG,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,EAAG,MAAM,CAAC;IACpB,IAAI,EAAE,GAAG,CAAC;IACV,SAAS,EAAG,MAAM,CAAC;IACnB,SAAS,EAAG,IAAI,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,GAAG,EAAE,CAAC;CACpB;AAED,qBAAa,YAAY;IACvB,SAAS,EAAG,IAAI,CAAC;IACjB,KAAK,EAAG,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,GAAG,EAAE,CAAC;IACnB,SAAS,EAAG,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,GAAG,CAAC;CACZ;AAED,qBAAa,yBAAyB;IACpC,SAAS,EAAG,MAAM,CAAC;IACnB,aAAa,EAAG,MAAM,CAAC;IACvB,UAAU,EAAG,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB"}
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ApproveTransactionPayload = exports.EmitQueryDTO = exports.CreateEventDTO = exports.UpdateEventDTO = exports.CreateAuditLogDto = void 0;
4
+ class CreateAuditLogDto {
5
+ }
6
+ exports.CreateAuditLogDto = CreateAuditLogDto;
7
+ class UpdateEventDTO {
8
+ }
9
+ exports.UpdateEventDTO = UpdateEventDTO;
10
+ class CreateEventDTO {
11
+ }
12
+ exports.CreateEventDTO = CreateEventDTO;
13
+ class EmitQueryDTO {
14
+ }
15
+ exports.EmitQueryDTO = EmitQueryDTO;
16
+ class ApproveTransactionPayload {
17
+ }
18
+ exports.ApproveTransactionPayload = ApproveTransactionPayload;
@@ -0,0 +1,20 @@
1
+ export declare enum EAuditLogRequestMethod {
2
+ GET = "GET",
3
+ POST = "POST",
4
+ PUT = "PUT",
5
+ DELETE = "DELETE",
6
+ PATCH = "PATCH",
7
+ EVENT = "EVENT"
8
+ }
9
+ export declare const ClientLoggerInterceptor = "AUDIT_LOGGER_RMQ_CLIENT";
10
+ export declare const AuditLoggerRMQQueue = "audit";
11
+ export declare const AuditLoggerRMQTopic = "audit-log-topic";
12
+ export declare const AuditDeadLetterExchange = "dead_letter_exchange";
13
+ export declare const DeadAuditRoutingKey = "audit.dead";
14
+ export declare const RegisterRequestAudit = "register-request-audit";
15
+ export declare const CommitRequestAudit = "commit-request-audit";
16
+ export declare const RollbackRequestAudit = "rollback-request-audit";
17
+ export declare const RecordInsertion = "record-insertion";
18
+ export declare const RecordUpdate = "record-update";
19
+ export declare const RecordDeletion = "record-delete";
20
+ //# sourceMappingURL=mezgeb.enum.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mezgeb.enum.d.ts","sourceRoot":"","sources":["../../libs/mezgeb/src/mezgeb/mezgeb.enum.ts"],"names":[],"mappings":"AAAA,oBAAY,sBAAsB;IAChC,GAAG,QAAQ;IACX,IAAI,SAAS;IACb,GAAG,QAAQ;IACX,MAAM,WAAW;IACjB,KAAK,UAAU;IACf,KAAK,UAAU;CAChB;AAED,eAAO,MAAM,uBAAuB,4BAA4B,CAAC;AACjE,eAAO,MAAM,mBAAmB,UAAU,CAAC;AAC3C,eAAO,MAAM,mBAAmB,oBAAoB,CAAC;AACrD,eAAO,MAAM,uBAAuB,yBAAyB,CAAC;AAC9D,eAAO,MAAM,mBAAmB,eAAe,CAAC;AAEhD,eAAO,MAAM,oBAAoB,2BAA2B,CAAC;AAC7D,eAAO,MAAM,kBAAkB,yBAAyB,CAAC;AACzD,eAAO,MAAM,oBAAoB,2BAA2B,CAAC;AAC7D,eAAO,MAAM,eAAe,qBAAqB,CAAC;AAClD,eAAO,MAAM,YAAY,kBAAkB,CAAC;AAC5C,eAAO,MAAM,cAAc,kBAAkB,CAAC"}
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RecordDeletion = exports.RecordUpdate = exports.RecordInsertion = exports.RollbackRequestAudit = exports.CommitRequestAudit = exports.RegisterRequestAudit = exports.DeadAuditRoutingKey = exports.AuditDeadLetterExchange = exports.AuditLoggerRMQTopic = exports.AuditLoggerRMQQueue = exports.ClientLoggerInterceptor = exports.EAuditLogRequestMethod = void 0;
4
+ var EAuditLogRequestMethod;
5
+ (function (EAuditLogRequestMethod) {
6
+ EAuditLogRequestMethod["GET"] = "GET";
7
+ EAuditLogRequestMethod["POST"] = "POST";
8
+ EAuditLogRequestMethod["PUT"] = "PUT";
9
+ EAuditLogRequestMethod["DELETE"] = "DELETE";
10
+ EAuditLogRequestMethod["PATCH"] = "PATCH";
11
+ EAuditLogRequestMethod["EVENT"] = "EVENT";
12
+ })(EAuditLogRequestMethod || (exports.EAuditLogRequestMethod = EAuditLogRequestMethod = {}));
13
+ exports.ClientLoggerInterceptor = 'AUDIT_LOGGER_RMQ_CLIENT';
14
+ exports.AuditLoggerRMQQueue = 'audit';
15
+ exports.AuditLoggerRMQTopic = 'audit-log-topic';
16
+ exports.AuditDeadLetterExchange = 'dead_letter_exchange';
17
+ exports.DeadAuditRoutingKey = 'audit.dead';
18
+ exports.RegisterRequestAudit = 'register-request-audit';
19
+ exports.CommitRequestAudit = 'commit-request-audit';
20
+ exports.RollbackRequestAudit = 'rollback-request-audit';
21
+ exports.RecordInsertion = 'record-insertion';
22
+ exports.RecordUpdate = 'record-update';
23
+ exports.RecordDeletion = 'record-delete';
@@ -0,0 +1,17 @@
1
+ import { EAuditLogRequestMethod } from "./mezgeb.enum";
2
+ export type TAuditLog = {
3
+ requestMethod: EAuditLogRequestMethod;
4
+ application: string;
5
+ module: string;
6
+ requestBody: any;
7
+ requestHeader: any;
8
+ statusCode: number;
9
+ ipAddress: string;
10
+ executionTime: number;
11
+ objectIds: string[];
12
+ userId: any;
13
+ userName: any;
14
+ organizationId: any;
15
+ organizationName: any;
16
+ };
17
+ //# sourceMappingURL=mezgeb.type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mezgeb.type.d.ts","sourceRoot":"","sources":["../../libs/mezgeb/src/mezgeb/mezgeb.type.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAEvD,MAAM,MAAM,SAAS,GAAG;IACtB,aAAa,EAAE,sBAAsB,CAAC;IACtC,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,GAAG,CAAC;IACjB,aAAa,EAAE,GAAG,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,CAAC;IACZ,QAAQ,EAAE,GAAG,CAAC;IACd,cAAc,EAAE,GAAG,CAAC;IACpB,gBAAgB,EAAE,GAAG,CAAC;CACvB,CAAC"}
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,3 @@
1
+ export declare class MezgebModule {
2
+ }
3
+ //# sourceMappingURL=mezgeb.module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mezgeb.module.d.ts","sourceRoot":"","sources":["../libs/mezgeb/src/mezgeb.module.ts"],"names":[],"mappings":"AAGA,qBAOa,YAAY;CAAG"}
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.MezgebModule = void 0;
10
+ const common_1 = require("@nestjs/common");
11
+ const client_module_1 = require("./mezgeb/client/client.module");
12
+ let MezgebModule = class MezgebModule {
13
+ };
14
+ exports.MezgebModule = MezgebModule;
15
+ exports.MezgebModule = MezgebModule = __decorate([
16
+ (0, common_1.Module)({
17
+ imports: [
18
+ client_module_1.ClientModule
19
+ ],
20
+ providers: [],
21
+ exports: [],
22
+ })
23
+ ], MezgebModule);
@@ -0,0 +1,2 @@
1
+ export * from './mezgeb/client/client.module';
2
+ export * from './mezgeb.module';
@@ -0,0 +1,176 @@
1
+ import {
2
+ CallHandler,
3
+ ExecutionContext,
4
+ Inject,
5
+ Injectable,
6
+ NestInterceptor,
7
+ } from '@nestjs/common';
8
+ import { Reflector } from '@nestjs/core';
9
+ import { catchError, finalize, map, Observable } from 'rxjs';
10
+ import { ClientProxy } from '@nestjs/microservices';
11
+ import { DataSource } from 'typeorm';
12
+ import { randomUUID } from 'crypto';
13
+ import { AUDIT_RMQ_EVENT } from './event-audit.decorator';
14
+ import { IGNORE_AUDIT_LOGGER } from './ignore-logger.decorator';
15
+ import { ApproveTransactionPayload, CreateAuditLogDto } from '../mezgeb.dto';
16
+ import { CommitRequestAudit, EAuditLogRequestMethod, RegisterRequestAudit, RollbackRequestAudit } from '../mezgeb.enum';
17
+
18
+ @Injectable()
19
+ export class ClientLoggerInterceptor implements NestInterceptor {
20
+ constructor(
21
+ private reflector: Reflector,
22
+ private readonly connection: DataSource,
23
+ @Inject(ClientLoggerInterceptor)
24
+ private readonly rmsRMQClient: ClientProxy,
25
+ ) {}
26
+
27
+ intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
28
+ const auditRmqEvent = this.reflector.getAllAndOverride<boolean>(
29
+ AUDIT_RMQ_EVENT,
30
+ [context.getHandler(), context.getClass()],
31
+ );
32
+
33
+ const isAuditIgnored = this.reflector.getAllAndOverride<boolean>(
34
+ IGNORE_AUDIT_LOGGER,
35
+ [context.getHandler(), context.getClass()],
36
+ );
37
+
38
+ if (isAuditIgnored) return next.handle();
39
+
40
+ if (
41
+ !auditRmqEvent &&
42
+ context.switchToHttp().getRequest().method == EAuditLogRequestMethod.GET
43
+ )
44
+ return next.handle();
45
+
46
+ const ds: any = this.connection;
47
+ const requestId: string = (ds.requestId = randomUUID());
48
+ const startTime = Date.now();
49
+
50
+ if (auditRmqEvent)
51
+ this.handleEventAuditInitiation(context, next, requestId);
52
+ else this.handleRequestAuditInitiation(context, next, requestId);
53
+
54
+ return next.handle().pipe(
55
+ map((resp) => {
56
+ const { statusCode } = context.switchToHttp().getResponse();
57
+ this.handleTransaction('Commit', statusCode, requestId, startTime);
58
+ return resp;
59
+ }),
60
+ catchError((error) => {
61
+ const statusCode = error.status ?? error.code;
62
+ this.handleTransaction(
63
+ 'Rollback',
64
+ statusCode,
65
+ requestId,
66
+ startTime,
67
+ error?.message,
68
+ );
69
+ throw error;
70
+ }),
71
+ finalize(() => {
72
+ const ds: any = this.connection;
73
+ ds.user = null;
74
+ ds.requestId = null;
75
+ }),
76
+ );
77
+ }
78
+
79
+ private handleRequestAuditInitiation(
80
+ context: ExecutionContext,
81
+ next: CallHandler,
82
+ requestId: string,
83
+ ) {
84
+ const req = context.switchToHttp().getRequest();
85
+
86
+ const { ip, ips, method, originalUrl, headers, body, params, user } = req;
87
+
88
+ const ds: any = this.connection;
89
+ const userPayload = (ds.user = {
90
+ id: user?.id,
91
+ name: `${user?.firstName} ${user?.lastName}`,
92
+ organizationId: user?.organization?.id,
93
+ organizationName: user?.organization?.name,
94
+ });
95
+
96
+ const log: CreateAuditLogDto = {
97
+ id: requestId,
98
+ requestMethod: method,
99
+ application: process.env.APPLICATION_NAME!,
100
+ module: originalUrl.split('/')[2],
101
+ requestBody: originalUrl.includes('/auth') ? {} : body,
102
+ requestHeader: this.mapHeaders(headers),
103
+ statusCode: 201,
104
+ ipAddress: ips?.length ? ips[0] : ip,
105
+ executionTime: 0,
106
+ user: userPayload,
107
+ };
108
+
109
+ this.rmsRMQClient.emit(RegisterRequestAudit, log);
110
+ }
111
+
112
+ private handleEventAuditInitiation(
113
+ context: any,
114
+ next: CallHandler,
115
+ requestId: string,
116
+ ) {
117
+ const eventPayload = context.getArgs()[0];
118
+ const eventPattern = context.getArgs()[1].args[2];
119
+
120
+ const ds: any = this.connection;
121
+ const userPayload = (ds.user = {});
122
+
123
+ const log: CreateAuditLogDto = {
124
+ id: requestId,
125
+ requestMethod: EAuditLogRequestMethod.EVENT,
126
+ application: process.env.APPLICATION_NAME!,
127
+ module: eventPattern,
128
+ requestBody: eventPayload,
129
+ requestHeader: {},
130
+ statusCode: 201,
131
+ ipAddress: '-',
132
+ executionTime: 0,
133
+ user: userPayload,
134
+ };
135
+
136
+ this.rmsRMQClient.emit(RegisterRequestAudit, log);
137
+ }
138
+
139
+ private handleTransaction(
140
+ type: 'Commit' | 'Rollback',
141
+ statusCode: number,
142
+ requestId: string,
143
+ startTime: number,
144
+ remark?: string,
145
+ ) {
146
+ const executionTime = Date.now() - startTime;
147
+
148
+ const approvePayload: ApproveTransactionPayload = {
149
+ requestId,
150
+ executionTime,
151
+ statusCode,
152
+ remark,
153
+ };
154
+
155
+ this.rmsRMQClient.emit(
156
+ type == 'Commit' ? CommitRequestAudit : RollbackRequestAudit,
157
+ approvePayload,
158
+ );
159
+ }
160
+
161
+ private mapHeaders(headers: any) {
162
+ return {
163
+ ...headers,
164
+ authorization: headers?.authorization ? 'Bearer [REDACTED]' : undefined,
165
+ cookie: headers?.cookie ? this.mapCookies(headers.cookie) : undefined,
166
+ };
167
+ }
168
+
169
+ private mapCookies(cookie: string): string[] {
170
+ return cookie.split(';').reduce((acc: string[], c: string) => {
171
+ const [key] = c.split('=').map((part) => part.trim());
172
+ acc.push(key);
173
+ return acc;
174
+ }, []);
175
+ }
176
+ }
@@ -0,0 +1,24 @@
1
+ import { Transport } from '@nestjs/microservices';
2
+ import { AuditDeadLetterExchange, ClientLoggerInterceptor, AuditLoggerRMQQueue, DeadAuditRoutingKey } from '../mezgeb.enum';
3
+
4
+
5
+ export const auditLoggerConfig: any = {
6
+ name: ClientLoggerInterceptor,
7
+ transport: Transport.RMQ,
8
+ options: {
9
+ urls: [process.env.RMQ_URL],
10
+ queue: AuditLoggerRMQQueue,
11
+ prefetchCount: 1,
12
+ noAck: false,
13
+ isGlobalPrefetchCount: true,
14
+ socketOptions: {
15
+ frameMax: 16384,
16
+ heartbeat: 60,
17
+ },
18
+ queueOptions: {
19
+ durable: true,
20
+ deadLetterExchange: AuditDeadLetterExchange,
21
+ deadLetterRoutingKey: DeadAuditRoutingKey,
22
+ },
23
+ },
24
+ };
@@ -0,0 +1,18 @@
1
+ import { Module } from '@nestjs/common';
2
+ import { APP_INTERCEPTOR } from '@nestjs/core';
3
+ import { ClientsModule, Transport } from '@nestjs/microservices';
4
+ import { auditLoggerConfig } from './client.logger.config';
5
+ import { ClientLoggerInterceptor } from './client-audit.interceptor';
6
+ import { ClientSubscriber } from './client.subscriber';
7
+
8
+ @Module({
9
+ imports: [ClientsModule.register([auditLoggerConfig])],
10
+ providers: [
11
+ {
12
+ provide: APP_INTERCEPTOR,
13
+ useClass: ClientLoggerInterceptor,
14
+ },
15
+ ClientSubscriber,
16
+ ],
17
+ })
18
+ export class AuditClientModule {}
@@ -0,0 +1,60 @@
1
+ import { Inject } from '@nestjs/common';
2
+ import { ClientProxy } from '@nestjs/microservices';
3
+ import {
4
+ AfterQueryEvent,
5
+ DataSource,
6
+ EntitySubscriberInterface,
7
+ EventSubscriber,
8
+ InsertEvent,
9
+ } from 'typeorm';
10
+ import { CreateEventDTO, EmitQueryDTO } from '../mezgeb.dto';
11
+ import { ClientLoggerInterceptor, RecordDeletion, RecordInsertion, RecordUpdate } from '../mezgeb.enum';
12
+
13
+
14
+ @EventSubscriber()
15
+ export class ClientSubscriber implements EntitySubscriberInterface {
16
+ constructor(
17
+ private readonly dataSource: DataSource,
18
+ @Inject(ClientLoggerInterceptor)
19
+ private readonly rmsRMQClient: ClientProxy,
20
+ ) {
21
+ dataSource.subscribers.push(this);
22
+ }
23
+
24
+ afterInsert(event: InsertEvent<any>): Promise<any> | void {
25
+ const ds: any = this.dataSource;
26
+ const payload: CreateEventDTO = {
27
+ user: ds.user,
28
+ entityName: event.metadata.tableName,
29
+ entityId: event.entity.id,
30
+ entity: event.entity,
31
+ requestId: ds.requestId,
32
+ query: 'INSERT',
33
+ createdAt: new Date(),
34
+ };
35
+ this.rmsRMQClient.emit(RecordInsertion, payload);
36
+ }
37
+
38
+ afterQuery(event: AfterQueryEvent<any>): Promise<any> | void {
39
+ if (
40
+ !event.success ||
41
+ !(event.query.startsWith('DELETE') || event.query.startsWith('UPDATE'))
42
+ ) {
43
+ return;
44
+ }
45
+
46
+ const ds: any = this.dataSource;
47
+ const payload: EmitQueryDTO = {
48
+ createdAt: new Date(),
49
+ query: event.query,
50
+ requestId: ds.requestId,
51
+ parameters: event.parameters,
52
+ user: ds.user,
53
+ };
54
+
55
+ this.rmsRMQClient.emit(
56
+ event.query.startsWith('DELETE') ? RecordDeletion : RecordUpdate,
57
+ payload,
58
+ );
59
+ }
60
+ }
@@ -0,0 +1,4 @@
1
+ import { SetMetadata } from '@nestjs/common';
2
+
3
+ export const AUDIT_RMQ_EVENT = 'AuditRmqEvent';
4
+ export const AuditRmqEvent = () => SetMetadata(AUDIT_RMQ_EVENT, true);
@@ -0,0 +1,4 @@
1
+ import { SetMetadata } from '@nestjs/common';
2
+
3
+ export const IGNORE_AUDIT_LOGGER = 'ignoreAuditLogger';
4
+ export const IgnoreLoggerAudit = () => SetMetadata(IGNORE_AUDIT_LOGGER, true);
@@ -0,0 +1,50 @@
1
+ import { EAuditLogRequestMethod } from "./mezgeb.enum";
2
+
3
+ export class CreateAuditLogDto {
4
+ requestMethod!: EAuditLogRequestMethod;
5
+ id!: string;
6
+ application!: string;
7
+ module!: string;
8
+ requestBody!: any;
9
+ requestHeader!: any;
10
+ statusCode!: number;
11
+ ipAddress!: string;
12
+ executionTime!: number;
13
+ user!: any;
14
+ }
15
+
16
+ export class UpdateEventDTO {
17
+ entityId?: string;
18
+ entityName!: string;
19
+ user: any;
20
+ requestId!: string;
21
+ whereParams?: Record<string, any>;
22
+ setParams?: Record<string, any>;
23
+ createdAt!: Date;
24
+ }
25
+
26
+ export class CreateEventDTO {
27
+ entity: any;
28
+ entityId?: string;
29
+ entityName!: string;
30
+ user: any;
31
+ requestId!: string;
32
+ createdAt!: Date;
33
+ query?: string;
34
+ parameters?: any[];
35
+ }
36
+
37
+ export class EmitQueryDTO {
38
+ createdAt!: Date;
39
+ query!: string;
40
+ parameters?: any[];
41
+ requestId!: string;
42
+ user?: any;
43
+ }
44
+
45
+ export class ApproveTransactionPayload {
46
+ requestId!: string;
47
+ executionTime!: number;
48
+ statusCode!: number;
49
+ remark?: string;
50
+ }
@@ -0,0 +1,21 @@
1
+ export enum EAuditLogRequestMethod {
2
+ GET = 'GET',
3
+ POST = 'POST',
4
+ PUT = 'PUT',
5
+ DELETE = 'DELETE',
6
+ PATCH = 'PATCH',
7
+ EVENT = 'EVENT',
8
+ }
9
+
10
+ export const ClientLoggerInterceptor = 'AUDIT_LOGGER_RMQ_CLIENT';
11
+ export const AuditLoggerRMQQueue = 'audit';
12
+ export const AuditLoggerRMQTopic = 'audit-log-topic';
13
+ export const AuditDeadLetterExchange = 'dead_letter_exchange';
14
+ export const DeadAuditRoutingKey = 'audit.dead';
15
+
16
+ export const RegisterRequestAudit = 'register-request-audit';
17
+ export const CommitRequestAudit = 'commit-request-audit';
18
+ export const RollbackRequestAudit = 'rollback-request-audit';
19
+ export const RecordInsertion = 'record-insertion';
20
+ export const RecordUpdate = 'record-update';
21
+ export const RecordDeletion = 'record-delete';
@@ -0,0 +1,17 @@
1
+ import { EAuditLogRequestMethod } from "./mezgeb.enum";
2
+
3
+ export type TAuditLog = {
4
+ requestMethod: EAuditLogRequestMethod;
5
+ application: string;
6
+ module: string;
7
+ requestBody: any;
8
+ requestHeader: any;
9
+ statusCode: number;
10
+ ipAddress: string;
11
+ executionTime: number;
12
+ objectIds: string[];
13
+ userId: any;
14
+ userName: any;
15
+ organizationId: any;
16
+ organizationName: any;
17
+ };
@@ -0,0 +1,11 @@
1
+ import { Module } from '@nestjs/common';
2
+ import { AuditClientModule } from './mezgeb/client/client.module';
3
+
4
+ @Module({
5
+ imports: [
6
+ AuditClientModule
7
+ ],
8
+ providers: [],
9
+ exports: [],
10
+ })
11
+ export class MezgebModule {}
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "declaration": true,
5
+ "outDir": "../../dist/libs/mezgeb"
6
+ },
7
+ "include": ["src/**/*"],
8
+ "exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
9
+ }
package/nest-cli.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "projects": {
3
+ "mezgeb": {
4
+ "type": "library",
5
+ "root": "libs/mezgeb",
6
+ "entryFile": "index",
7
+ "sourceRoot": "libs/mezgeb/src",
8
+ "compilerOptions": {
9
+ "tsConfigPath": "libs/mezgeb/tsconfig.lib.json"
10
+ }
11
+ }
12
+ },
13
+ "compilerOptions": {
14
+ "webpack": false
15
+ }
16
+ }
package/package.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "@estgbue/mezgeb",
3
+ "version": "0.0.1",
4
+ "dependencies": {
5
+ "@nestjs/common": "^11.1.10",
6
+ "@nestjs/core": "^11.1.10",
7
+ "@nestjs/microservices": "^11.1.10",
8
+ "@nestjs/typeorm": "^11.0.0",
9
+ "crypto": "^1.0.1",
10
+ "rxjs": "^7.8.2",
11
+ "typeorm": "^0.3.28"
12
+ },
13
+ "devDependencies": {
14
+ "@types/node": "^25.0.3"
15
+ }
16
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,105 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig to read more about this file */
4
+
5
+ "outDir": "./dist",
6
+
7
+ /* Projects */
8
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
9
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
10
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
11
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
12
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
13
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
14
+
15
+ /* Language and Environment */
16
+ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
17
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
18
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
19
+ "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
20
+ "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
21
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
22
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
23
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
24
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
25
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
26
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
27
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
28
+
29
+ /* Modules */
30
+ "module": "commonjs", /* Specify what module code is generated. */
31
+ // "rootDir": "./", /* Specify the root folder within your source files. */
32
+ // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
33
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
34
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
35
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
36
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
37
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
38
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
39
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
40
+ // "resolveJsonModule": true, /* Enable importing .json files. */
41
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
42
+
43
+ /* JavaScript Support */
44
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
45
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
46
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
47
+
48
+ /* Emit */
49
+ "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
50
+ "declarationMap": true, /* Create sourcemaps for d.ts files. */
51
+ "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
52
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
53
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
54
+ // "outDir": "./", /* Specify an output folder for all emitted files. */
55
+ // "removeComments": true, /* Disable emitting comments. */
56
+ // "noEmit": true, /* Disable emitting files from a compilation. */
57
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
58
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
59
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
60
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
61
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
62
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
63
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
64
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
65
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
66
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
67
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
68
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
69
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
70
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
71
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
72
+
73
+ /* Interop Constraints */
74
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
75
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
76
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
77
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
78
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
79
+
80
+ /* Type Checking */
81
+ "strict": true, /* Enable all strict type-checking options. */
82
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
83
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
84
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
85
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
86
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
87
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
88
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
89
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
90
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
91
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
92
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
93
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
94
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
95
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
96
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
97
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
98
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
99
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
100
+
101
+ /* Completeness */
102
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
103
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
104
+ }
105
+ }