-
Notifications
You must be signed in to change notification settings - Fork 59
/
hooks.js
65 lines (56 loc) · 1.41 KB
/
hooks.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const debug = require('debug')('feathers-knex-transaction');
const start = (options) => {
return hook => new Promise(resolve => {
if (!hook.service.Model || typeof hook.service.Model.transaction !== 'function') {
return resolve(hook);
}
if (hook.params.transaction) {
hook.params.transaction.count += 1;
return resolve(hook);
}
hook.service.Model.transaction(trx => {
const id = Date.now();
hook.params.transaction = {
trx,
id,
count: 0
};
debug('started a new transaction %s', id);
return resolve(hook);
});
});
};
const end = (options) => {
return hook => {
if (hook.params.transaction) {
const { trx, id, count } = hook.params.transaction;
if (count > 0) {
hook.params.transaction.count -= 1;
return Promise.resolve(hook);
}
hook.params.transaction = undefined;
return trx.commit()
.then(() => debug('finished transaction %s with success', id))
.then(() => hook);
}
return hook;
};
};
const rollback = (options) => {
return hook => {
if (hook.params.transaction) {
const { trx, id } = hook.params.transaction;
return trx.rollback(hook.error)
.then(() => debug('rolling back transaction %s', id))
.then(() => hook);
}
return hook;
};
};
module.exports = {
transaction: {
start,
end,
rollback
}
};