Documentation / @andrew_l/mongo-transaction / useTransactionEffect
Function: useTransactionEffect() ​
useTransactionEffect(
setup
,options
):Promise
<void
>
Executes a transactional effect with cleanup on error or rollback.
Ensures the callback
function is executed only once per transaction, even during retries. On errors or dependency changes, the cleanup logic is invoked before re-execution to maintain consistency.
Parameters ​
• setup: EffectCallback
A function defining the transactional effect. It is guaranteed to run once per transaction and may be re-executed after cleanup if dependencies change.
• options: Partial
<Pick
<TransactionEffect
, "name"
| "flush"
| "dependencies"
>> = {}
Returns ​
Promise
<void
>
Example ​
ts
const confirmOrder = withMongoTransaction({
connection: () => mongoose.connection.getClient(),
async fn(session) {
// Register an alert as a transactional effect
await useTransactionEffect(async () => {
const alertId = await alertService.create({
title: `Order Confirmed: ${orderId}`,
});
// Define cleanup logic to remove the alert on rollback
return () => alertService.removeById(alertId);
});
// Simulate order processing (e.g., database updates)
await db
.collection('orders')
.updateOne({ orderId }, { $set: { status: 'confirmed' } }, { session });
// Simulate an error to test rollback
throw new Error('Simulated transaction failure');
},
});