fix(db operations): Update transaction API to consistently pass optional session parameters across database operations
This commit is contained in:
19
readme.md
19
readme.md
@@ -409,19 +409,23 @@ class Product extends SmartDataDbDoc<Product, Product> {
|
||||
|
||||
### Transaction Support
|
||||
|
||||
Use MongoDB transactions for atomic operations:
|
||||
Use MongoDB transactions for atomic operations. SmartData now exposes `startSession()` and accepts an optional session in all fetch and write APIs:
|
||||
|
||||
```typescript
|
||||
const session = await db.startSession();
|
||||
// start a client session (no await)
|
||||
const session = db.startSession();
|
||||
try {
|
||||
// wrap operations in a transaction
|
||||
await session.withTransaction(async () => {
|
||||
const user = await User.getInstance({ id: 'user-id' }, { session });
|
||||
// pass session as second arg to getInstance
|
||||
const user = await User.getInstance({ id: 'user-id' }, session);
|
||||
user.balance -= 100;
|
||||
// pass session in save opts
|
||||
await user.save({ session });
|
||||
|
||||
const recipient = await User.getInstance({ id: 'recipient-id' }, { session });
|
||||
const recipient = await User.getInstance({ id: 'recipient-id' }, session);
|
||||
recipient.balance += 100;
|
||||
await user.save({ session });
|
||||
await recipient.save({ session });
|
||||
});
|
||||
} finally {
|
||||
await session.endSession();
|
||||
@@ -518,6 +522,11 @@ class Order extends SmartDataDbDoc<Order, Order> {
|
||||
throw new Error('Order cannot be deleted');
|
||||
}
|
||||
}
|
||||
// Called after deleting the document
|
||||
async afterDelete() {
|
||||
// Cleanup or audit actions
|
||||
await auditLogDeletion(this.id);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user