Skip to content

Commit 7aaf160

Browse files
authoredFeb 9, 2020
adding transaction hook
1 parent 165288f commit 7aaf160

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
 

‎hooks/sequelize-transaction-hook.js

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/* eslint-disable require-atomic-updates */
2+
const start = (options = {}) => {
3+
return async hook => {
4+
if (
5+
hook.params.transaction ||
6+
(hook.params.sequelize && options.params.sequelize.transaction)
7+
) {
8+
// already in transaction probably in diffrent hook or service
9+
// so we dont create or commit the transaction in this service
10+
return hook;
11+
}
12+
13+
const sequelize = await hook.app.get("sequelizeClient");
14+
const transaction = await sequelize.transaction();
15+
16+
hook.params.transaction = transaction;
17+
hook.params.transactionOwner = hook.path;
18+
hook.params.sequelize = hook.params.sequelize || {};
19+
hook.params.sequelize.transaction = transaction;
20+
21+
return hook;
22+
};
23+
};
24+
25+
const end = () => {
26+
return hook => {
27+
const { params } = hook.params;
28+
if (
29+
!params ||
30+
!params.transactionOwner ||
31+
params.transactionOwner !== hook.path
32+
) {
33+
// transaction probably from diffrent hook or service
34+
// so we dont commit or rollback the transaction in this service
35+
return hook;
36+
}
37+
const trx = params.sequelize.transacrion || params.transacrion;
38+
return trx.then(t => t.commit()).then(() => hook);
39+
};
40+
};
41+
42+
const rollback = () => {
43+
return hook => {
44+
const { params } = hook.params;
45+
if (
46+
!params ||
47+
!params.transactionOwner ||
48+
params.transactionOwner !== hook.path
49+
) {
50+
// transaction probably from diffrent hook or service
51+
// so we dont commit or rollback the transaction in this service
52+
return hook;
53+
}
54+
const trx = params.sequelize.transacrion || params.transacrion;
55+
return trx.then(t => t.rollback()).then(() => hook);
56+
};
57+
};
58+
59+
module.exports = {
60+
transaction: {
61+
start,
62+
end,
63+
rollback
64+
}
65+
};

0 commit comments

Comments
 (0)