forked from feathersjs-ecosystem/feathers-sequelize
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1 from yohane55/transaction-hook
adding transaction hook
- Loading branch information
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
/* eslint-disable require-atomic-updates */ | ||
const start = (options = {}) => { | ||
return async hook => { | ||
if ( | ||
hook.params.transaction || | ||
(hook.params.sequelize && options.params.sequelize.transaction) | ||
) { | ||
// already in transaction probably in diffrent hook or service | ||
// so we dont create or commit the transaction in this service | ||
return hook; | ||
} | ||
|
||
const sequelize = await hook.app.get("sequelizeClient"); | ||
const transaction = await sequelize.transaction(); | ||
|
||
hook.params.transaction = transaction; | ||
hook.params.transactionOwner = hook.path; | ||
hook.params.sequelize = hook.params.sequelize || {}; | ||
hook.params.sequelize.transaction = transaction; | ||
|
||
return hook; | ||
}; | ||
}; | ||
|
||
const end = () => { | ||
return hook => { | ||
const { params } = hook.params; | ||
if ( | ||
!params || | ||
!params.transactionOwner || | ||
params.transactionOwner !== hook.path | ||
) { | ||
// transaction probably from diffrent hook or service | ||
// so we dont commit or rollback the transaction in this service | ||
return hook; | ||
} | ||
const trx = params.sequelize.transacrion || params.transacrion; | ||
return trx.then(t => t.commit()).then(() => hook); | ||
}; | ||
}; | ||
|
||
const rollback = () => { | ||
return hook => { | ||
const { params } = hook.params; | ||
if ( | ||
!params || | ||
!params.transactionOwner || | ||
params.transactionOwner !== hook.path | ||
) { | ||
// transaction probably from diffrent hook or service | ||
// so we dont commit or rollback the transaction in this service | ||
return hook; | ||
} | ||
const trx = params.sequelize.transacrion || params.transacrion; | ||
return trx.then(t => t.rollback()).then(() => hook); | ||
}; | ||
}; | ||
|
||
module.exports = { | ||
transaction: { | ||
start, | ||
end, | ||
rollback | ||
} | ||
}; |