@autofleet/shtinker 1.1.7-beta.9 → 1.1.7-beta2

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/shtinker",
3
- "version": "1.1.7-beta.9",
3
+ "version": "1.1.7-beta2",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -18,6 +18,7 @@
18
18
  "@autofleet/netwrok": "^1.0.0",
19
19
  "@autofleet/rabbit": "^3.2.18",
20
20
  "@autofleet/zehut": "^3.0.10",
21
+ "object-diff": "^0.0.4",
21
22
  "sequelize-typescript": "^2.1.5"
22
23
  },
23
24
  "devDependencies": {
@@ -3,9 +3,12 @@ import { Sequelize } from 'sequelize';
3
3
 
4
4
  import { AuditLogPayload, AuditLoggerOptions, AuditLogContext } from './types';
5
5
  import { AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUDIT_LOG_CONTEXT_KEY } from './const';
6
+ import diff from 'object-diff';
6
7
 
7
8
  import logger from './logger';
8
9
 
10
+ const CUSTOM_FIELDS_PROPERTY = 'customFields';
11
+
9
12
  const getAuditContext = () => {
10
13
  const currentTrace = getCurrentTrace();
11
14
  const auditContext = currentTrace?.context?.get(AUDIT_LOG_CONTEXT_KEY);
@@ -30,8 +33,37 @@ const filterOutEmptyFields = (fields, instance) => fields.filter((field) => !isE
30
33
  const getChangedFields = (instance, options) => {
31
34
  // When bulk updating in sequelize using the "returning" option, the instance.changed() stops working.
32
35
  // It's a known issut with sequelize.
33
- const changedProperties = options.returning ? options.fields : instance.changed();
34
- return filterOutEmptyFields(changedProperties, instance);
36
+ const changedFields = options.returning ? options.fields : instance.changed();
37
+ //Filter customFields - we'll handle them later
38
+ const filteredChangedProperties = changedFields.filter(p => p !== CUSTOM_FIELDS_PROPERTY);
39
+ return filterOutEmptyFields(filteredChangedProperties, instance);
40
+ };
41
+
42
+ const getChangedFieldsRows = (instance, changedFields: string[]) => changedFields.map((property: string) => ({
43
+ property,
44
+ previousValue: instance.previous(property),
45
+ newValue: instance.get(property),
46
+ }));
47
+
48
+ const getChangedCustomFields = (instance) => {
49
+ const customFieldsChanged = instance.changed().includes(CUSTOM_FIELDS_PROPERTY);
50
+ if (!customFieldsChanged) {
51
+ return [];
52
+ }
53
+ const customFieldsValues = instance.get(CUSTOM_FIELDS_PROPERTY);
54
+ const previousCustomFieldsValues = instance.previous(CUSTOM_FIELDS_PROPERTY);
55
+ const diffObj = diff(previousCustomFieldsValues, customFieldsValues);
56
+ return Object.keys(diffObj).filter((field) => !isEmpty(customFieldsValues?.[field]) || !isEmpty(previousCustomFieldsValues?.[field]));
57
+ };
58
+
59
+ const getChangedCustomFieldsRows = (instance, changedCustomFields: string[]) => {
60
+ const customFieldsValues = instance.get(CUSTOM_FIELDS_PROPERTY);
61
+ const previousCustomFieldsValues = instance.previous(CUSTOM_FIELDS_PROPERTY);
62
+ return changedCustomFields.map((changedCustomField) => ({
63
+ property: `customFields.${changedCustomField}`,
64
+ previousValue: previousCustomFieldsValues?.[changedCustomField],
65
+ newValue: customFieldsValues?.[changedCustomField],
66
+ }));
35
67
  };
36
68
 
37
69
  class AuditLogger {
@@ -53,15 +85,14 @@ class AuditLogger {
53
85
  try {
54
86
  const auditContext = getAuditContext();
55
87
  if (auditContext) {
56
- const changedProperties = getChangedFields(instance, options);
88
+ const changedFields = getChangedFields(instance, options);
89
+ const changedFieldsRows = getChangedFieldsRows(instance, changedFields);
90
+ const changedCustomFields = getChangedCustomFields(instance);
91
+ const changedCustomFieldsRows = getChangedCustomFieldsRows(instance, changedCustomFields);
57
92
  const payload: AuditLogPayload = {
58
93
  entityType: modelName,
59
94
  entityId: instance.id,
60
- rows: changedProperties.map((property: string) => ({
61
- property,
62
- previousValue: instance.previous(property),
63
- newValue: instance.get(property),
64
- })),
95
+ rows: [...changedFieldsRows, ...changedCustomFieldsRows],
65
96
  };
66
97
  this.sendAuditLogRows(payload);
67
98
  }
package/src/index.ts CHANGED
@@ -8,11 +8,9 @@ import logger from './logger';
8
8
  let auditLogger: AuditLogger;
9
9
 
10
10
  export const enableAuditing = (options: AuditLoggerOptions) => {
11
- if (process.env.DISABLE_AUDIT_LOGS !== 'true') {
12
- auditLogger = new AuditLogger(options);
13
- addAuditApi(options as any);
14
- auditLogger.registerHooks();
15
- }
11
+ auditLogger = new AuditLogger(options);
12
+ addAuditApi(options as any);
13
+ auditLogger.registerHooks();
16
14
  };
17
15
 
18
16
  export const setAuditContext = (
@@ -20,9 +18,6 @@ export const setAuditContext = (
20
18
  action: string,
21
19
  ) => async (req: any, res: any, next: any): Promise<any> => {
22
20
  try {
23
- if (process.env.DISABLE_AUDIT_LOGS === 'true') {
24
- return next();
25
- }
26
21
  const currentTrace = getCurrentTrace();
27
22
  if (currentTrace && currentTrace.context && currentTrace.context.get) {
28
23
  const user = currentTrace.context.get(USER_CONTEXT_KEY);
@@ -46,9 +41,6 @@ export const setRabbitAuditContext = (
46
41
  entityType: string,
47
42
  action: string,
48
43
  ) => async (endpoint: string): Promise<any> => {
49
- if (process.env.DISABLE_AUDIT_LOGS === 'true') {
50
- return;
51
- }
52
44
  const currentTrace = getCurrentTrace();
53
45
  if (currentTrace?.context?.get) {
54
46
  const user = currentTrace.context.get(USER_CONTEXT_KEY);
@@ -1,6 +0,0 @@
1
- import { Router } from 'express';
2
- declare const _default: ({ router, entiyScopedModelMap, }: {
3
- router: Router;
4
- entiyScopedModelMap: Array<any>;
5
- }) => Promise<void>;
6
- export default _default;
package/dist/audit-api.js DELETED
@@ -1,36 +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
- const errors_1 = require("@autofleet/errors");
16
- const audit_ms_1 = __importDefault(require("./audit-ms"));
17
- exports.default = ({ router, entiyScopedModelMap, }) => __awaiter(void 0, void 0, void 0, function* () {
18
- if (entiyScopedModelMap) {
19
- Object.entries(entiyScopedModelMap).forEach(([entity, ScopedModel]) => {
20
- router.get(`${entity}/:id/audit`, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
21
- try {
22
- const { id } = req.params;
23
- const entityData = yield ScopedModel.findByPk(id);
24
- if (!entityData) {
25
- return (0, errors_1.handleError)(new errors_1.ResourceNotFoundError(), res);
26
- }
27
- const auditData = audit_ms_1.default.getByEntityId(id);
28
- return res.json(auditData);
29
- }
30
- catch (err) {
31
- return (0, errors_1.handleError)(new errors_1.UnexpectedError(err), res);
32
- }
33
- }));
34
- });
35
- }
36
- });
@@ -1,11 +0,0 @@
1
- import { AuditLogPayload, AuditLoggerOptions, AuditLogContext } from './types';
2
- declare class AuditLogger {
3
- private rabbit;
4
- private sequelize;
5
- private logger;
6
- constructor(options: AuditLoggerOptions);
7
- registerHooks(): void;
8
- sendAuditLogContext(context: AuditLogContext): Promise<void>;
9
- sendAuditLogRows(payload: AuditLogPayload): Promise<void>;
10
- }
11
- export default AuditLogger;
@@ -1,95 +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
- const zehut_1 = require("@autofleet/zehut");
16
- const const_1 = require("./const");
17
- const logger_1 = __importDefault(require("./logger"));
18
- const getAuditContext = () => {
19
- var _a;
20
- const currentTrace = (0, zehut_1.getCurrentPayload)();
21
- const auditContext = (_a = currentTrace === null || currentTrace === void 0 ? void 0 : currentTrace.context) === null || _a === void 0 ? void 0 : _a.get(const_1.AUDIT_LOG_CONTEXT_KEY);
22
- return auditContext;
23
- };
24
- const isEmpty = (field) => {
25
- if ([null, undefined].includes(field)) {
26
- return true;
27
- }
28
- if (Array.isArray(field)) {
29
- return field.length === 0;
30
- }
31
- if (typeof field === 'object' && !(field instanceof Date)) {
32
- return Object.keys(field).length === 0;
33
- }
34
- return false;
35
- };
36
- const filterOutEmptyFields = (fields, instance) => fields.filter((field) => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));
37
- const getChangedFields = (instance, options) => {
38
- // When bulk updating in sequelize using the "returning" option, the instance.changed() stops working.
39
- // It's a known issut with sequelize.
40
- const changedProperties = options.returning ? options.fields : instance.changed();
41
- return filterOutEmptyFields(changedProperties, instance);
42
- };
43
- class AuditLogger {
44
- constructor(options) {
45
- this.rabbit = options.rabbit;
46
- this.sequelize = options.sequelize;
47
- this.logger = options.logger;
48
- }
49
- registerHooks() {
50
- Object.entries(this.sequelize.models).forEach(([modelName, modelType]) => {
51
- modelType.addHook('afterSave', (instance, options) => __awaiter(this, void 0, void 0, function* () {
52
- try {
53
- const auditContext = getAuditContext();
54
- if (auditContext) {
55
- const changedProperties = getChangedFields(instance, options);
56
- const payload = {
57
- entityType: modelName,
58
- entityId: instance.id,
59
- rows: changedProperties.map((property) => ({
60
- property,
61
- previousValue: instance.previous(property),
62
- newValue: instance.get(property),
63
- })),
64
- };
65
- this.sendAuditLogRows(payload);
66
- }
67
- }
68
- catch (error) {
69
- logger_1.default.error('Failed to send audit log rows', error);
70
- }
71
- }));
72
- });
73
- }
74
- sendAuditLogContext(context) {
75
- return __awaiter(this, void 0, void 0, function* () {
76
- try {
77
- yield this.rabbit.sendToQueue(const_1.AUDIT_LOG_CONTEXT_QUEUE, context);
78
- }
79
- catch (err) {
80
- logger_1.default.error('Failed to send audit log context', err);
81
- }
82
- });
83
- }
84
- sendAuditLogRows(payload) {
85
- return __awaiter(this, void 0, void 0, function* () {
86
- try {
87
- yield this.rabbit.sendToQueue(const_1.AUDIT_LOG_ROWS_QUEUE, payload);
88
- }
89
- catch (err) {
90
- logger_1.default.error('Failed to send audit log rows', err);
91
- }
92
- });
93
- }
94
- }
95
- exports.default = AuditLogger;
@@ -1,4 +0,0 @@
1
- declare const _default: {
2
- getByEntityId: (entityId: string) => any;
3
- };
4
- export default _default;
package/dist/audit-ms.js DELETED
@@ -1,14 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const network_1 = __importDefault(require("@autofleet/network"));
7
- const auditMs = new network_1.default({ serviceName: 'AUDIT_MS', timeout: 1000 * 60 });
8
- const getByEntityId = (entityId) => {
9
- const { data } = auditMs.get(`api/v1/audit-logs/${entityId}`);
10
- return data;
11
- };
12
- exports.default = {
13
- getByEntityId,
14
- };
package/dist/const.d.ts DELETED
@@ -1,4 +0,0 @@
1
- export declare const AUDIT_LOG_CONTEXT_QUEUE = "audit-log-context";
2
- export declare const AUDIT_LOG_ROWS_QUEUE = "audit-log-rows";
3
- export declare const AUDIT_LOG_CONTEXT_KEY = "auditLogContext";
4
- export declare const USER_CONTEXT_KEY = "userObject";
package/dist/const.js DELETED
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.USER_CONTEXT_KEY = exports.AUDIT_LOG_CONTEXT_KEY = exports.AUDIT_LOG_ROWS_QUEUE = exports.AUDIT_LOG_CONTEXT_QUEUE = void 0;
4
- exports.AUDIT_LOG_CONTEXT_QUEUE = 'audit-log-context';
5
- exports.AUDIT_LOG_ROWS_QUEUE = 'audit-log-rows';
6
- exports.AUDIT_LOG_CONTEXT_KEY = 'auditLogContext';
7
- exports.USER_CONTEXT_KEY = 'userObject';
package/dist/index.d.ts DELETED
@@ -1,8 +0,0 @@
1
- import AuditLogger from './audit-logger';
2
- import { AuditLoggerOptions } from './types';
3
- export declare const enableAuditing: (options: AuditLoggerOptions) => void;
4
- export declare const setAuditContext: (entityType: string, action: string) => (req: any, res: any, next: any) => Promise<any>;
5
- export declare const setRabbitAuditContext: (entityType: string, action: string) => (endpoint: string) => Promise<any>;
6
- export * from './types';
7
- export * from './const';
8
- export default AuditLogger;
package/dist/index.js DELETED
@@ -1,91 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __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
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
17
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18
- return new (P || (P = Promise))(function (resolve, reject) {
19
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
20
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22
- step((generator = generator.apply(thisArg, _arguments || [])).next());
23
- });
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.setRabbitAuditContext = exports.setAuditContext = exports.enableAuditing = void 0;
30
- const zehut_1 = require("@autofleet/zehut");
31
- const audit_logger_1 = __importDefault(require("./audit-logger"));
32
- const const_1 = require("./const");
33
- const audit_api_1 = __importDefault(require("./audit-api"));
34
- const logger_1 = __importDefault(require("./logger"));
35
- let auditLogger;
36
- const enableAuditing = (options) => {
37
- if (process.env.DISABLE_AUDIT_LOGS !== 'true') {
38
- auditLogger = new audit_logger_1.default(options);
39
- (0, audit_api_1.default)(options);
40
- auditLogger.registerHooks();
41
- }
42
- };
43
- exports.enableAuditing = enableAuditing;
44
- const setAuditContext = (entityType, action) => (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
45
- try {
46
- if (process.env.DISABLE_AUDIT_LOGS === 'true') {
47
- return next();
48
- }
49
- const currentTrace = (0, zehut_1.getCurrentPayload)();
50
- if (currentTrace && currentTrace.context && currentTrace.context.get) {
51
- const user = currentTrace.context.get(const_1.USER_CONTEXT_KEY);
52
- const auditLogContext = {
53
- entityType,
54
- action,
55
- endpoint: req.url,
56
- method: req.method,
57
- performedBy: user === null || user === void 0 ? void 0 : user.id,
58
- };
59
- currentTrace.context.set(const_1.AUDIT_LOG_CONTEXT_KEY, auditLogContext);
60
- yield auditLogger.sendAuditLogContext(auditLogContext);
61
- }
62
- }
63
- catch (err) {
64
- logger_1.default.error('coudln\'t set audit context', err);
65
- }
66
- return next();
67
- });
68
- exports.setAuditContext = setAuditContext;
69
- const setRabbitAuditContext = (entityType, action) => (endpoint) => __awaiter(void 0, void 0, void 0, function* () {
70
- var _a;
71
- if (process.env.DISABLE_AUDIT_LOGS === 'true') {
72
- return;
73
- }
74
- const currentTrace = (0, zehut_1.getCurrentPayload)();
75
- if ((_a = currentTrace === null || currentTrace === void 0 ? void 0 : currentTrace.context) === null || _a === void 0 ? void 0 : _a.get) {
76
- const user = currentTrace.context.get(const_1.USER_CONTEXT_KEY);
77
- const auditLogContext = {
78
- entityType,
79
- action,
80
- endpoint,
81
- method: 'rabbit',
82
- performedBy: user === null || user === void 0 ? void 0 : user.id,
83
- };
84
- currentTrace.context.set(const_1.AUDIT_LOG_CONTEXT_KEY, auditLogContext);
85
- yield auditLogger.sendAuditLogContext(auditLogContext);
86
- }
87
- });
88
- exports.setRabbitAuditContext = setRabbitAuditContext;
89
- __exportStar(require("./types"), exports);
90
- __exportStar(require("./const"), exports);
91
- exports.default = audit_logger_1.default;
package/dist/logger.d.ts DELETED
@@ -1,2 +0,0 @@
1
- declare const _default: import("@autofleet/logger").LoggerInstanceManager;
2
- export default _default;
package/dist/logger.js DELETED
@@ -1,7 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const logger_1 = __importDefault(require("@autofleet/logger"));
7
- exports.default = (0, logger_1.default)(null);
package/dist/types.d.ts DELETED
@@ -1,48 +0,0 @@
1
- import { Sequelize } from 'sequelize-typescript';
2
- import RabbitMq from '@autofleet/rabbit';
3
- export type AuditLoggerOptions = {
4
- rabbit: RabbitMq;
5
- sequelize: Sequelize;
6
- logger: any;
7
- };
8
- export interface AuditLogContext {
9
- entityType: string;
10
- action: string;
11
- performedBy: string;
12
- endpoint: string;
13
- method: string;
14
- }
15
- export interface AuditLogRow {
16
- property: string;
17
- previousValue: any;
18
- newValue: any;
19
- }
20
- export interface AuditLogPayload {
21
- entityType: string;
22
- entityId: string;
23
- rows: AuditLogRow[];
24
- }
25
- export declare enum Action {
26
- CREATE = "create",
27
- BULK_CREATE = "bulk-create",
28
- BULK_EDIT = "bulk-edit",
29
- DELETE = "delete",
30
- UPDATE = "update",
31
- CANCEL = "cancel",
32
- FAIL = "fail",
33
- UNASSIGN = "unassign",
34
- BULK_ASSIGN = "bulk-assign",
35
- REASSIGN = "reassign",
36
- DISPATCH = "dispatch",
37
- BULK_DISPATCH = "bulk-dispatch",
38
- BULK_UPSERT = "bulk-upsert",
39
- UPSERT = "upsert",
40
- JOIN = "join",
41
- MOVE = "move"
42
- }
43
- export declare enum EntityType {
44
- RIDE = "Ride",
45
- VEHICLE = "Vehicle",
46
- DRIVER = "Driver",
47
- PRICE_CALCULATION = "PriceCalculation"
48
- }
package/dist/types.js DELETED
@@ -1,29 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EntityType = exports.Action = void 0;
4
- var Action;
5
- (function (Action) {
6
- Action["CREATE"] = "create";
7
- Action["BULK_CREATE"] = "bulk-create";
8
- Action["BULK_EDIT"] = "bulk-edit";
9
- Action["DELETE"] = "delete";
10
- Action["UPDATE"] = "update";
11
- Action["CANCEL"] = "cancel";
12
- Action["FAIL"] = "fail";
13
- Action["UNASSIGN"] = "unassign";
14
- Action["BULK_ASSIGN"] = "bulk-assign";
15
- Action["REASSIGN"] = "reassign";
16
- Action["DISPATCH"] = "dispatch";
17
- Action["BULK_DISPATCH"] = "bulk-dispatch";
18
- Action["BULK_UPSERT"] = "bulk-upsert";
19
- Action["UPSERT"] = "upsert";
20
- Action["JOIN"] = "join";
21
- Action["MOVE"] = "move";
22
- })(Action = exports.Action || (exports.Action = {}));
23
- var EntityType;
24
- (function (EntityType) {
25
- EntityType["RIDE"] = "Ride";
26
- EntityType["VEHICLE"] = "Vehicle";
27
- EntityType["DRIVER"] = "Driver";
28
- EntityType["PRICE_CALCULATION"] = "PriceCalculation";
29
- })(EntityType = exports.EntityType || (exports.EntityType = {}));