@autofleet/sequelize-utils 5.2.2 → 5.2.4

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.
@@ -0,0 +1,2 @@
1
+ import debug from 'debug';
2
+ export declare const debugLog: debug.Debugger;
package/dist/common.js ADDED
@@ -0,0 +1,8 @@
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
+ exports.debugLog = void 0;
7
+ const debug_1 = __importDefault(require("debug"));
8
+ exports.debugLog = (0, debug_1.default)('sequelize-utils');
@@ -0,0 +1,3 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { Sequelize, Transaction } from 'sequelize';
3
+ export declare const httpBasedTransaction: <T>(sequelize: Sequelize, req: IncomingMessage, res: ServerResponse, cb: (transaction: Transaction) => Promise<T>) => Promise<T>;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.httpBasedTransaction = void 0;
4
+ const common_1 = require("./common");
5
+ const rollbackErrorText = 'rollback has been called on this transaction';
6
+ const abortErrorText = 'Transaction cancelled due to request cancellation';
7
+ const httpBasedTransaction = (sequelize, req, res, cb) => {
8
+ let aborted = false;
9
+ if (req.socket.destroyed) {
10
+ (0, common_1.debugLog)(abortErrorText);
11
+ throw new Error(abortErrorText);
12
+ }
13
+ return sequelize.transaction(async (transaction) => {
14
+ // https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/test/parallel/test-http-aborted.js#L9
15
+ // 2023-04-13: Node.js 16.0.0
16
+ // Added also the `res.writableFinished` check, because it seems that the socket is not destroyed when the request is aborted, but the response is not finished.
17
+ // https://github.com/Jimbly/http-proxy-node16/commit/ba0c414cd03799e357c5d867c11dea06a9c34ec8#diff-b2d1e3b7c5f3b424a0af7971c582c822fd25a5ea279040ef6dc93fc4b2cf619dR151
18
+ const rollback = async () => {
19
+ (0, common_1.debugLog)(abortErrorText);
20
+ if (aborted)
21
+ return;
22
+ aborted = true;
23
+ await transaction.rollback();
24
+ };
25
+ const resRollback = async () => {
26
+ const didNotFinishWrite = !res.writableFinished;
27
+ if (didNotFinishWrite) {
28
+ (0, common_1.debugLog)(abortErrorText);
29
+ if (aborted)
30
+ return;
31
+ aborted = true;
32
+ await transaction.rollback();
33
+ }
34
+ };
35
+ req.socket.once('close', rollback);
36
+ res.once('close', resRollback);
37
+ const removeListeners = () => {
38
+ req.socket.removeListener('close', rollback);
39
+ res.removeListener('close', resRollback);
40
+ };
41
+ try {
42
+ const response = await cb(transaction);
43
+ removeListeners();
44
+ return response;
45
+ }
46
+ catch (e) {
47
+ removeListeners();
48
+ if (e.message.includes(rollbackErrorText)) {
49
+ throw new Error(abortErrorText);
50
+ }
51
+ throw e;
52
+ }
53
+ });
54
+ };
55
+ exports.httpBasedTransaction = httpBasedTransaction;
package/dist/index.d.ts CHANGED
@@ -1,8 +1,14 @@
1
- import { Sequelize } from 'sequelize';
1
+ import type { Sequelize, Transaction } from 'sequelize';
2
+ import addModelEventHooks from './model-event-hooks';
3
+ import { transactionWithRetry as _transactionWithRetry } from './transaction-with-retry';
4
+ import { httpBasedTransaction as _httpBasedTransaction } from './http-based-transaction';
5
+ import runAfterTransactionCommits from './runAfterTransactionCommits';
6
+ type ArgsWithoutSequelize<T> = T extends (arg1: Sequelize, ...args: infer U) => any ? U : never;
2
7
  declare const _default: (sequelize: Sequelize) => {
3
- transactionWithRetry: any;
4
- httpBasedTransaction: any;
5
- registerModelEventHooks: any;
6
- runAfterTransactionCommits: any;
8
+ transactionWithRetry: <T>(...args: ArgsWithoutSequelize<typeof _transactionWithRetry<T>>) => Promise<T>;
9
+ httpBasedTransaction: <T>(...args: ArgsWithoutSequelize<typeof _httpBasedTransaction<T>>) => Promise<T>;
10
+ registerModelEventHooks: (...args: ArgsWithoutSequelize<typeof addModelEventHooks>) => void;
11
+ runAfterTransactionCommits: typeof runAfterTransactionCommits;
12
+ useOrCreateTransaction: <T>(transaction: Transaction, cb: (t: Transaction) => Promise<T>) => Promise<T>;
7
13
  };
8
14
  export default _default;
package/dist/index.js CHANGED
@@ -3,97 +3,25 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- /* eslint-disable import/prefer-default-export */
7
- const sequelize_1 = require("sequelize");
8
- const debug_1 = __importDefault(require("debug"));
9
6
  const model_event_hooks_1 = __importDefault(require("./model-event-hooks"));
10
- const log = debug_1.default('sequelize-utils');
11
- const rollbackErrorText = 'rollback has been called on this transaction';
12
- const abortErrorText = 'Transaction cancelled due to request cancellation';
7
+ const transaction_with_retry_1 = require("./transaction-with-retry");
8
+ const http_based_transaction_1 = require("./http-based-transaction");
9
+ const runAfterTransactionCommits_1 = __importDefault(require("./runAfterTransactionCommits"));
13
10
  exports.default = (sequelize) => {
14
- const transactionWithRetry = async (funcToRun, retriesCount = 2, options) => {
15
- try {
16
- const transValue = await sequelize.transaction(options || {}, async (transaction) => {
17
- const funcValue = await funcToRun(transaction);
18
- return funcValue;
19
- });
20
- return transValue;
21
- }
22
- catch (e) {
23
- if (e instanceof sequelize_1.DatabaseError || e?.constructor?.name === 'DatabaseError') {
24
- if (retriesCount === 0) {
25
- log('error inside transactionWithRetry - will stop retry', e);
26
- throw e;
27
- }
28
- log(`error inside transactionWithRetry - will retry times ${retriesCount - 1}`, e);
29
- return transactionWithRetry(funcToRun, retriesCount - 1);
30
- }
31
- throw e;
32
- }
33
- };
34
- // eslint-disable-next-line @typescript-eslint/ban-types
35
- const httpBasedTransaction = (req, res, cb) => {
36
- let aborted = false;
37
- if (req.socket.destroyed) {
38
- log(abortErrorText);
39
- throw new Error(abortErrorText);
40
- }
41
- return sequelize.transaction(async (transaction) => {
42
- // https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/test/parallel/test-http-aborted.js#L9
43
- // 2023-04-13: Node.js 16.0.0
44
- // Added also the res.writableFinished check, becurse it seems that the socket is not destroyed
45
- // when the request is aborted, but the response is not finished.
46
- // https://github.com/Jimbly/http-proxy-node16/commit/ba0c414cd03799e357c5d867c11dea06a9c34ec8#diff-b2d1e3b7c5f3b424a0af7971c582c822fd25a5ea279040ef6dc93fc4b2cf619dR151
47
- const rollback = async () => {
48
- log(abortErrorText);
49
- if (aborted)
50
- return;
51
- aborted = true;
52
- await transaction.rollback();
53
- };
54
- const resRollback = async () => {
55
- const didNotFinishWrite = !res.writableFinished;
56
- if (didNotFinishWrite) {
57
- log(abortErrorText);
58
- if (aborted)
59
- return;
60
- aborted = true;
61
- await transaction.rollback();
62
- }
63
- };
64
- req.socket.once('close', rollback);
65
- res.once('close', resRollback);
66
- const removeListeners = () => {
67
- req.socket.removeListener('close', rollback);
68
- res.removeListener('close', resRollback);
69
- };
70
- try {
71
- const response = await cb(transaction);
72
- removeListeners();
73
- return response;
74
- }
75
- catch (e) {
76
- removeListeners();
77
- if (e.message.includes(rollbackErrorText)) {
78
- throw new Error(abortErrorText);
79
- }
80
- throw e;
81
- }
82
- });
83
- };
84
- const registerModelEventHooks = (modelTableMapping) => model_event_hooks_1.default(sequelize, modelTableMapping);
85
- const runAfterTransactionCommits = (cb, options) => {
86
- if (options.transaction) {
87
- options.transaction.afterCommit(() => cb());
88
- }
89
- else {
90
- cb();
11
+ const transactionWithRetry = (funcToRun, retriesCount, options) => (0, transaction_with_retry_1.transactionWithRetry)(sequelize, funcToRun, retriesCount, options);
12
+ const httpBasedTransaction = (req, res, cb) => (0, http_based_transaction_1.httpBasedTransaction)(sequelize, req, res, cb);
13
+ const registerModelEventHooks = (modelTableMapping) => (0, model_event_hooks_1.default)(sequelize, modelTableMapping);
14
+ const useOrCreateTransaction = (transaction, cb) => {
15
+ if (transaction) {
16
+ return cb(transaction);
91
17
  }
18
+ return transactionWithRetry(cb, 0);
92
19
  };
93
20
  return {
94
21
  httpBasedTransaction,
95
22
  transactionWithRetry,
96
23
  registerModelEventHooks,
97
- runAfterTransactionCommits,
24
+ runAfterTransactionCommits: runAfterTransactionCommits_1.default,
25
+ useOrCreateTransaction,
98
26
  };
99
27
  };
package/dist/logger.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- declare const _default: any;
1
+ declare const _default: import("@autofleet/logger").LoggerInstanceManager;
2
2
  export default _default;
package/dist/logger.js CHANGED
@@ -4,4 +4,4 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const logger_1 = __importDefault(require("@autofleet/logger"));
7
- exports.default = logger_1.default();
7
+ exports.default = (0, logger_1.default)();
@@ -1,8 +1,8 @@
1
- import { Sequelize } from 'sequelize';
2
- interface ModelMapping {
1
+ import type { Sequelize } from 'sequelize';
2
+ export interface ModelMapping {
3
3
  [ModelName: string]: {
4
4
  tableName: string;
5
5
  };
6
6
  }
7
- declare const addModelEventHooks: (sequelize: Sequelize, modelTableMapping: ModelMapping) => Promise<void>;
7
+ declare const addModelEventHooks: (sequelize: Sequelize, modelTableMapping: ModelMapping) => void;
8
8
  export default addModelEventHooks;
@@ -5,48 +5,37 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const events_1 = __importDefault(require("./events"));
7
7
  const logger_1 = __importDefault(require("./logger"));
8
+ const runAfterTransactionCommits_1 = __importDefault(require("./runAfterTransactionCommits"));
9
+ const isDate = (input) => input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
10
+ // eslint-disable-next-line @typescript-eslint/ban-types
8
11
  const formatDatesInObject = (obj) => {
9
12
  const newObj = { ...obj };
10
- Object.keys(newObj).forEach((key) => {
11
- if (newObj[key] instanceof Date) {
12
- newObj[key] = newObj[key].getTime() / 1000;
13
- }
13
+ Object.entries(newObj).filter(([, value]) => isDate(value)).forEach(([key, value]) => {
14
+ newObj[key] = value.getTime() / 1000;
14
15
  });
15
16
  return newObj;
16
17
  };
17
- const addModelEventHooks = async (sequelize, modelTableMapping) => {
18
- const updateEventToDimTable = (object, isDelete = false) => {
18
+ const addModelEventHooks = (sequelize, modelTableMapping) => {
19
+ const updateEventToDimTable = async (object, isDelete = false) => {
19
20
  try {
20
21
  const objectToSend = object.get();
21
22
  if (isDelete) {
22
- objectToSend.deletedAt = new Date();
23
+ Object.assign(objectToSend, { deletedAt: new Date() });
23
24
  }
24
25
  const tableName = modelTableMapping[object.constructor.name]?.tableName;
25
26
  const eventVersion = '1';
26
27
  const objectToSendFormatted = formatDatesInObject(objectToSend);
27
28
  if (tableName) {
28
- events_1.default.sendObject(tableName, eventVersion, objectToSendFormatted, Object.keys(object.rawAttributes));
29
+ await events_1.default.sendObject(tableName, eventVersion, objectToSendFormatted,
30
+ // @ts-expect-error the rawAttributes is typed as static, while it actually is on the instance level.
31
+ Object.keys(object.rawAttributes));
29
32
  }
30
33
  }
31
34
  catch (e) {
32
35
  logger_1.default.error('dimTables error', { e });
33
36
  }
34
37
  };
35
- sequelize.addHook('afterSave', async (savedObject, options) => {
36
- if (options.transaction) {
37
- options.transaction.afterCommit(() => updateEventToDimTable(savedObject));
38
- }
39
- else {
40
- await updateEventToDimTable(savedObject);
41
- }
42
- });
43
- sequelize.addHook('afterDestroy', async (savedObject, options) => {
44
- if (options.transaction) {
45
- options.transaction.afterCommit(() => updateEventToDimTable(savedObject, true));
46
- }
47
- else {
48
- await updateEventToDimTable(savedObject, true);
49
- }
50
- });
38
+ sequelize.addHook('afterSave', (savedObject, options) => (0, runAfterTransactionCommits_1.default)(() => updateEventToDimTable(savedObject), options));
39
+ sequelize.addHook('afterDestroy', (savedObject, options) => (0, runAfterTransactionCommits_1.default)(() => updateEventToDimTable(savedObject, true), options));
51
40
  };
52
41
  exports.default = addModelEventHooks;
@@ -0,0 +1,3 @@
1
+ import { Transactionable } from 'sequelize';
2
+ declare const runAfterTransactionCommits: (cb: () => unknown, options: Transactionable) => Promise<void>;
3
+ export default runAfterTransactionCommits;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const runAfterTransactionCommits = async (cb, options) => {
4
+ if (options.transaction) {
5
+ options.transaction.afterCommit(() => cb());
6
+ }
7
+ else {
8
+ await cb();
9
+ }
10
+ };
11
+ exports.default = runAfterTransactionCommits;
@@ -0,0 +1,2 @@
1
+ import { Sequelize } from 'sequelize';
2
+ export declare function createSequelizeInstance(): Sequelize;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSequelizeInstance = createSequelizeInstance;
4
+ const node_process_1 = require("node:process");
5
+ const sequelize_1 = require("sequelize");
6
+ function createSequelizeInstance() {
7
+ return new sequelize_1.Sequelize(node_process_1.env.DB_NAME || 'test_service_development', node_process_1.env.DB_USERNAME || '', node_process_1.env.DB_PASSWORD, {
8
+ host: node_process_1.env.DB_HOST || '127.0.0.1',
9
+ dialect: 'postgres',
10
+ operatorsAliases: sequelize_1.Op,
11
+ define: {
12
+ underscored: true,
13
+ },
14
+ pool: {
15
+ max: 10,
16
+ min: 1,
17
+ },
18
+ });
19
+ }
@@ -0,0 +1,2 @@
1
+ import { type Sequelize, type Transaction, type TransactionOptions } from 'sequelize';
2
+ export declare const transactionWithRetry: <T>(sequelize: Sequelize, funcToRun: (transaction: Transaction) => Promise<T>, retriesCount?: number, options?: TransactionOptions) => Promise<T>;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.transactionWithRetry = void 0;
4
+ const sequelize_1 = require("sequelize");
5
+ const common_1 = require("./common");
6
+ const transactionWithRetry = async (sequelize, funcToRun, retriesCount = 2, options = {}) => {
7
+ if (typeof funcToRun !== 'function') {
8
+ throw new Error('funcToRun must be a function');
9
+ }
10
+ if (typeof retriesCount !== 'number') {
11
+ throw new Error('if defined, retriesCount must be a number');
12
+ }
13
+ if (retriesCount < 0) {
14
+ throw new Error('retriesCount must be a positive number');
15
+ }
16
+ try {
17
+ const transValue = await sequelize.transaction(options, async (transaction) => {
18
+ const funcValue = await funcToRun(transaction);
19
+ return funcValue;
20
+ });
21
+ return transValue;
22
+ }
23
+ catch (e) {
24
+ if ((e instanceof sequelize_1.DatabaseError || e?.constructor?.name === 'DatabaseError') && --retriesCount >= 0) {
25
+ (0, common_1.debugLog)(`error inside transactionWithRetry - will retry times ${retriesCount}`, e);
26
+ return (0, exports.transactionWithRetry)(sequelize, funcToRun, retriesCount, options);
27
+ }
28
+ if (retriesCount === -1) {
29
+ (0, common_1.debugLog)('error inside transactionWithRetry - will stop retry', e);
30
+ }
31
+ throw e;
32
+ }
33
+ };
34
+ exports.transactionWithRetry = transactionWithRetry;
package/package.json CHANGED
@@ -1,49 +1,46 @@
1
1
  {
2
2
  "name": "@autofleet/sequelize-utils",
3
- "version": "5.2.2",
3
+ "version": "5.2.4",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
7
- "start": "ts-node src/index.ts",
8
- "example": "ts-node src/example.ts",
9
- "prepublish": "tsc",
10
- "build": "tsc",
11
- "lint": "./node_modules/.bin/eslint .",
12
- "test": "jest --forceExit",
13
- "test-local": "jest --forceExit",
14
- "coverage": "jest --coverage --forceExit --runInBand && rm -rf ./coverage"
15
- },
16
- "jest": {
17
- "testEnvironment": "node"
7
+ "start": "ts-node src/index.ts",
8
+ "prepublish": "tsc -p tsconfig.build.json",
9
+ "build": "tsc -p tsconfig.build.json",
10
+ "lint": "eslint .",
11
+ "test": "jest",
12
+ "test-local": "jest",
13
+ "coverage": "jest --coverage --runInBand"
18
14
  },
19
15
  "author": "",
20
16
  "license": "ISC",
21
17
  "dependencies": {
22
- "@autofleet/errors": "^1.1.0",
23
- "@autofleet/events": "^3.0.5",
24
- "@autofleet/logger": "^2.0.2",
18
+ "@autofleet/errors": "^1.2.3",
19
+ "@autofleet/events": "^3.0.7",
25
20
  "@autofleet/network": "^1.3.7",
26
- "debug": "^4.3.2",
27
- "jest": "^27.0.6",
28
- "sequelize": "^5.22.3"
21
+ "debug": "^4.3.2"
22
+ },
23
+ "peerDependencies": {
24
+ "@autofleet/logger": ">=4",
25
+ "sequelize": ">=5"
29
26
  },
30
27
  "devDependencies": {
31
- "@types/bluebird": "^3.5.36",
28
+ "@autofleet/logger": "^4.1.0",
32
29
  "@types/debug": "^4.1.6",
33
30
  "@types/express": "^4.17.13",
34
- "@types/jest": "^26.0.24",
35
- "@types/validator": "^13.6.3",
31
+ "@types/jest": "^29.5.14",
32
+ "@types/node": "^22.10.6",
36
33
  "@typescript-eslint/eslint-plugin": "^4.28.3",
37
34
  "@typescript-eslint/parser": "^4.28.3",
38
- "axios": "^0.26.1",
39
- "bluebird": "^3.7.2",
40
35
  "eslint": "^7.31.0",
41
36
  "eslint-config-airbnb-base": "^14.2.1",
42
37
  "eslint-plugin-import": "^2.23.4",
43
38
  "express": "^4.17.3",
44
- "pg": "^8.6.0",
45
- "ts-jest": "^27.0.3",
39
+ "jest": "^29.7.0",
40
+ "pg": "^8.13.1",
41
+ "sequelize": "^5.22.3",
42
+ "ts-jest": "^29.2.5",
46
43
  "ts-node": "^10.1.0",
47
- "typescript": "^4.3.5"
44
+ "typescript": "^5.5.4"
48
45
  }
49
46
  }
package/src/common.ts ADDED
@@ -0,0 +1,3 @@
1
+ import debug from 'debug';
2
+
3
+ export const debugLog = debug('sequelize-utils');
@@ -0,0 +1,56 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { Sequelize, Transaction } from 'sequelize';
3
+ import { debugLog } from './common';
4
+
5
+ const rollbackErrorText = 'rollback has been called on this transaction';
6
+ const abortErrorText = 'Transaction cancelled due to request cancellation';
7
+
8
+ export const httpBasedTransaction = <T>(sequelize: Sequelize, req: IncomingMessage, res: ServerResponse, cb: (transaction: Transaction) => Promise<T>): Promise<T> => {
9
+ let aborted = false;
10
+ if (req.socket.destroyed) {
11
+ debugLog(abortErrorText);
12
+ throw new Error(abortErrorText);
13
+ }
14
+ return sequelize.transaction(async (transaction: Transaction) => {
15
+ // https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/test/parallel/test-http-aborted.js#L9
16
+
17
+ // 2023-04-13: Node.js 16.0.0
18
+ // Added also the `res.writableFinished` check, because it seems that the socket is not destroyed when the request is aborted, but the response is not finished.
19
+ // https://github.com/Jimbly/http-proxy-node16/commit/ba0c414cd03799e357c5d867c11dea06a9c34ec8#diff-b2d1e3b7c5f3b424a0af7971c582c822fd25a5ea279040ef6dc93fc4b2cf619dR151
20
+
21
+ const rollback = async () => {
22
+ debugLog(abortErrorText);
23
+ if (aborted) return;
24
+ aborted = true;
25
+ await transaction.rollback();
26
+ };
27
+ const resRollback = async () => {
28
+ const didNotFinishWrite = !res.writableFinished;
29
+ if (didNotFinishWrite) {
30
+ debugLog(abortErrorText);
31
+ if (aborted) return;
32
+ aborted = true;
33
+ await transaction.rollback();
34
+ }
35
+ };
36
+ req.socket.once('close', rollback);
37
+ res.once('close', resRollback);
38
+
39
+ const removeListeners = () => {
40
+ req.socket.removeListener('close', rollback);
41
+ res.removeListener('close', resRollback);
42
+ };
43
+
44
+ try {
45
+ const response = await cb(transaction);
46
+ removeListeners();
47
+ return response;
48
+ } catch (e) {
49
+ removeListeners();
50
+ if (e.message.includes(rollbackErrorText)) {
51
+ throw new Error(abortErrorText);
52
+ }
53
+ throw e;
54
+ }
55
+ });
56
+ };
package/src/index.ts CHANGED
@@ -1,105 +1,32 @@
1
1
  /* eslint-disable import/prefer-default-export */
2
- import {
3
- DatabaseError,
2
+ import type {
4
3
  Sequelize,
5
4
  Transaction,
6
- Transactionable,
5
+ TransactionOptions,
7
6
  } from 'sequelize';
8
- import debug from 'debug';
9
- import addModelEventHooks from './model-event-hooks';
7
+ import type { IncomingMessage, ServerResponse } from 'http';
8
+ import addModelEventHooks, { ModelMapping } from './model-event-hooks';
9
+ import { transactionWithRetry as _transactionWithRetry } from './transaction-with-retry';
10
+ import { httpBasedTransaction as _httpBasedTransaction } from './http-based-transaction';
11
+ import runAfterTransactionCommits from './runAfterTransactionCommits';
10
12
 
11
- const log = debug('sequelize-utils');
12
-
13
- const rollbackErrorText = 'rollback has been called on this transaction';
14
- const abortErrorText = 'Transaction cancelled due to request cancellation';
13
+ type ArgsWithoutSequelize<T> = T extends (arg1: Sequelize, ...args: infer U) => any ? U : never;
15
14
 
16
15
  export default (sequelize: Sequelize): {
17
- transactionWithRetry: any,
18
- httpBasedTransaction: any,
19
- registerModelEventHooks: any,
20
- runAfterTransactionCommits: any,
16
+ transactionWithRetry: <T>(...args: ArgsWithoutSequelize<typeof _transactionWithRetry<T>>) => Promise<T>;
17
+ httpBasedTransaction: <T>(...args: ArgsWithoutSequelize<typeof _httpBasedTransaction<T>>) => Promise<T>;
18
+ registerModelEventHooks: (...args: ArgsWithoutSequelize<typeof addModelEventHooks>) => void;
19
+ runAfterTransactionCommits: typeof runAfterTransactionCommits;
20
+ useOrCreateTransaction: <T>(transaction: Transaction, cb: (t: Transaction) => Promise<T>) => Promise<T>;
21
21
  } => {
22
- const transactionWithRetry = async (funcToRun: any, retriesCount = 2, options?: any): Promise<any> => {
23
- try {
24
- const transValue = await sequelize.transaction(options || {},
25
- async (transaction) => {
26
- const funcValue = await funcToRun(transaction);
27
- return funcValue;
28
- });
29
- return transValue;
30
- } catch (e) {
31
- if (e instanceof DatabaseError || e?.constructor?.name === 'DatabaseError') {
32
- if (retriesCount === 0) {
33
- log('error inside transactionWithRetry - will stop retry', e);
34
- throw e;
35
- }
36
- log(`error inside transactionWithRetry - will retry times ${retriesCount - 1}`, e);
37
- return transactionWithRetry(funcToRun, retriesCount - 1);
38
- }
39
- throw e;
40
- }
41
- };
42
-
43
- // eslint-disable-next-line @typescript-eslint/ban-types
44
- const httpBasedTransaction = (req: any, res: any, cb: Function) => {
45
- let aborted = false;
46
- if (req.socket.destroyed) {
47
- log(abortErrorText);
48
- throw new Error(abortErrorText);
49
- }
50
- return sequelize.transaction(async (transaction: Transaction) => {
51
- // https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/test/parallel/test-http-aborted.js#L9
52
-
53
- // 2023-04-13: Node.js 16.0.0
54
- // Added also the res.writableFinished check, becurse it seems that the socket is not destroyed
55
- // when the request is aborted, but the response is not finished.
56
- // https://github.com/Jimbly/http-proxy-node16/commit/ba0c414cd03799e357c5d867c11dea06a9c34ec8#diff-b2d1e3b7c5f3b424a0af7971c582c822fd25a5ea279040ef6dc93fc4b2cf619dR151
57
-
58
- const rollback = async () => {
59
- log(abortErrorText);
60
- if (aborted) return;
61
- aborted = true;
62
- await transaction.rollback();
63
- };
64
- const resRollback = async () => {
65
- const didNotFinishWrite = !res.writableFinished;
66
- if (didNotFinishWrite) {
67
- log(abortErrorText);
68
- if (aborted) return;
69
- aborted = true;
70
- await transaction.rollback();
71
- }
72
- };
73
- req.socket.once('close', rollback);
74
- res.once('close', resRollback);
75
-
76
- const removeListeners = () => {
77
- req.socket.removeListener('close', rollback);
78
- res.removeListener('close', resRollback);
79
- };
80
-
81
- try {
82
- const response = await cb(transaction);
83
- removeListeners();
84
- return response;
85
- } catch (e) {
86
- removeListeners();
87
- if (e.message.includes(rollbackErrorText)) {
88
- throw new Error(abortErrorText);
89
- }
90
- throw e;
91
- }
92
- });
93
- };
94
-
95
- const registerModelEventHooks = (modelTableMapping) => addModelEventHooks(sequelize, modelTableMapping);
96
-
97
- const runAfterTransactionCommits = (cb: () => any, options: Transactionable) => {
98
- if (options.transaction) {
99
- options.transaction.afterCommit(() => cb());
100
- } else {
101
- cb();
22
+ const transactionWithRetry = <T>(funcToRun: (transaction: Transaction) => Promise<T>, retriesCount?: number, options?: TransactionOptions): Promise<T> => _transactionWithRetry(sequelize, funcToRun, retriesCount, options);
23
+ const httpBasedTransaction = <T>(req: IncomingMessage, res: ServerResponse, cb: (transaction: Transaction) => Promise<T>): Promise<T> => _httpBasedTransaction(sequelize, req, res, cb);
24
+ const registerModelEventHooks = (modelTableMapping: ModelMapping) => addModelEventHooks(sequelize, modelTableMapping);
25
+ const useOrCreateTransaction = <T>(transaction: Transaction, cb: (t: Transaction) => Promise<T>) => {
26
+ if (transaction) {
27
+ return cb(transaction);
102
28
  }
29
+ return transactionWithRetry(cb, 0);
103
30
  };
104
31
 
105
32
  return {
@@ -107,5 +34,6 @@ export default (sequelize: Sequelize): {
107
34
  transactionWithRetry,
108
35
  registerModelEventHooks,
109
36
  runAfterTransactionCommits,
37
+ useOrCreateTransaction,
110
38
  };
111
39
  };
@@ -1,38 +1,39 @@
1
- import { Sequelize } from 'sequelize';
1
+ import type { Model, Sequelize } from 'sequelize';
2
2
  import events from './events';
3
3
  import logger from './logger';
4
+ import runAfterTransactionCommits from './runAfterTransactionCommits';
4
5
 
5
- interface ModelMapping {
6
+ export interface ModelMapping {
6
7
  [ModelName: string]: {
7
8
  tableName: string
8
9
  };
9
10
  }
10
-
11
- const formatDatesInObject = (obj: any) => {
11
+ const isDate = (input: unknown): input is Date => input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
12
+ // eslint-disable-next-line @typescript-eslint/ban-types
13
+ const formatDatesInObject = (obj: object) => {
12
14
  const newObj = { ...obj };
13
- Object.keys(newObj).forEach((key) => {
14
- if (newObj[key] instanceof Date) {
15
- newObj[key] = newObj[key].getTime() / 1000;
16
- }
15
+ Object.entries(newObj).filter(([, value]) => isDate(value)).forEach(([key, value]) => {
16
+ newObj[key] = (value as Date).getTime() / 1000;
17
17
  });
18
18
  return newObj;
19
19
  };
20
20
 
21
- const addModelEventHooks = async (sequelize: Sequelize, modelTableMapping: ModelMapping) => {
22
- const updateEventToDimTable = (object, isDelete = false) => {
21
+ const addModelEventHooks = (sequelize: Sequelize, modelTableMapping: ModelMapping): void => {
22
+ const updateEventToDimTable = async (object: Model, isDelete = false) => {
23
23
  try {
24
24
  const objectToSend = object.get();
25
25
  if (isDelete) {
26
- objectToSend.deletedAt = new Date();
26
+ Object.assign(objectToSend, { deletedAt: new Date() });
27
27
  }
28
28
  const tableName = modelTableMapping[object.constructor.name]?.tableName;
29
29
  const eventVersion = '1';
30
30
  const objectToSendFormatted = formatDatesInObject(objectToSend);
31
31
  if (tableName) {
32
- events.sendObject(
32
+ await events.sendObject(
33
33
  tableName,
34
34
  eventVersion,
35
35
  objectToSendFormatted,
36
+ // @ts-expect-error the rawAttributes is typed as static, while it actually is on the instance level.
36
37
  Object.keys(object.rawAttributes),
37
38
  );
38
39
  }
@@ -41,20 +42,8 @@ const addModelEventHooks = async (sequelize: Sequelize, modelTableMapping: Model
41
42
  }
42
43
  };
43
44
 
44
- sequelize.addHook('afterSave', async (savedObject, options) => {
45
- if (options.transaction) {
46
- options.transaction.afterCommit(() => updateEventToDimTable(savedObject));
47
- } else {
48
- await updateEventToDimTable(savedObject);
49
- }
50
- });
51
- sequelize.addHook('afterDestroy', async (savedObject, options) => {
52
- if (options.transaction) {
53
- options.transaction.afterCommit(() => updateEventToDimTable(savedObject, true));
54
- } else {
55
- await updateEventToDimTable(savedObject, true);
56
- }
57
- });
45
+ sequelize.addHook('afterSave', (savedObject, options) => runAfterTransactionCommits(() => updateEventToDimTable(savedObject), options));
46
+ sequelize.addHook('afterDestroy', (savedObject, options) => runAfterTransactionCommits(() => updateEventToDimTable(savedObject, true), options));
58
47
  };
59
48
 
60
49
  export default addModelEventHooks;
@@ -0,0 +1,10 @@
1
+ import { Transactionable } from 'sequelize';
2
+
3
+ const runAfterTransactionCommits = async (cb: () => unknown, options: Transactionable): Promise<void> => {
4
+ if (options.transaction) {
5
+ options.transaction.afterCommit(() => cb());
6
+ } else {
7
+ await cb();
8
+ }
9
+ };
10
+ export default runAfterTransactionCommits;
@@ -0,0 +1,22 @@
1
+ import { env } from 'node:process';
2
+ import { Sequelize, Op } from 'sequelize';
3
+
4
+ export function createSequelizeInstance(): Sequelize {
5
+ return new Sequelize(
6
+ env.DB_NAME || 'test_service_development',
7
+ env.DB_USERNAME || '',
8
+ env.DB_PASSWORD,
9
+ {
10
+ host: env.DB_HOST || '127.0.0.1',
11
+ dialect: 'postgres',
12
+ operatorsAliases: Op,
13
+ define: {
14
+ underscored: true,
15
+ },
16
+ pool: {
17
+ max: 10,
18
+ min: 1,
19
+ },
20
+ },
21
+ );
22
+ }
@@ -0,0 +1,32 @@
1
+ import {
2
+ DatabaseError, type Sequelize, type Transaction, type TransactionOptions,
3
+ } from 'sequelize';
4
+ import { debugLog } from './common';
5
+
6
+ export const transactionWithRetry = async <T>(sequelize: Sequelize, funcToRun: (transaction: Transaction) => Promise<T>, retriesCount = 2, options: TransactionOptions = {}): Promise<T> => {
7
+ if (typeof funcToRun !== 'function') {
8
+ throw new Error('funcToRun must be a function');
9
+ }
10
+ if (typeof retriesCount !== 'number') {
11
+ throw new Error('if defined, retriesCount must be a number');
12
+ }
13
+ if (retriesCount < 0) {
14
+ throw new Error('retriesCount must be a positive number');
15
+ }
16
+ try {
17
+ const transValue = await sequelize.transaction(options, async (transaction) => {
18
+ const funcValue = await funcToRun(transaction);
19
+ return funcValue;
20
+ });
21
+ return transValue;
22
+ } catch (e) {
23
+ if ((e instanceof DatabaseError || e?.constructor?.name === 'DatabaseError') && --retriesCount >= 0) {
24
+ debugLog(`error inside transactionWithRetry - will retry times ${retriesCount}`, e);
25
+ return transactionWithRetry(sequelize, funcToRun, retriesCount, options);
26
+ }
27
+ if (retriesCount === -1) {
28
+ debugLog('error inside transactionWithRetry - will stop retry', e);
29
+ }
30
+ throw e;
31
+ }
32
+ };
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "exclude": [
4
+ "node_modules",
5
+ "dist/**/*",
6
+ "test-utils/**/*",
7
+ "**/*.test.*"
8
+ ]
9
+ }
package/tsconfig.json CHANGED
@@ -5,6 +5,12 @@
5
5
  "declaration": true,
6
6
  "outDir": "./dist",
7
7
  "strict": false,
8
- "esModuleInterop": true
9
- }
8
+ "esModuleInterop": true,
9
+ "skipLibCheck": true
10
+ },
11
+ "include": ["src/**/*"],
12
+ "exclude": [
13
+ "node_modules",
14
+ "dist/**/*"
15
+ ]
10
16
  }