How to share the transaction in multiple services?

Hi, This is more like a design question. I'm using Drizzle ORM in Express.js application. I have userService and auditService to update the database records. Before the database transaction, I basically call the services like this,
router.post('/', async (req, res) => {
userService.create('john')
auditService.log('Create user john')
})
router.post('/', async (req, res) => {
userService.create('john')
auditService.log('Create user john')
})
and then with the database transaction,
router.post('/', async (req, res) => {
await db.transaction(async (tx) => {
userService.create(tx, 'john')
auditService.log(tx, 'Create user john')
})
})
router.post('/', async (req, res) => {
await db.transaction(async (tx) => {
userService.create(tx, 'john')
auditService.log(tx, 'Create user john')
})
})
Note that in the above, I have to pass the tx transaction to every service function. Is there a more elegant way than passing the tx to every function?
2 Replies
Angelelz
Angelelz8mo ago
This is the way, this is very elegant imo. This is dependency injection
Angelelz
Angelelz8mo ago
Some people have suggested to use asynclocalstorage for this purpose but I honestly don't like it. You'll have to decide for yourself https://github.com/drizzle-team/drizzle-orm/issues/543
GitHub
[FEATURE]: AsyncLocalStorage for transactions · Issue #543 · drizzl...
Describe want to want The idea is to use AsyncLocalStorage for automatically detecting transaction context, without using transaction object. Example how it should look like: await db.transaction(a...
Want results from more Discord servers?
Add your server