TemplateCallback that receives OutboxScope with session and scoped publish function
Promise that resolves when all operations in the scope complete
Publishing multiple events atomically
await outbox.withScope(async ({ publish }) => {
// All three events in same transaction
await publish({ type: 'OrderCreated', orderId: '123' })
await publish({ type: 'InventoryReserved', items: [...] })
await publish({ type: 'InvoiceGenerated', invoiceId: '456' })
})
// Either all three succeed or all three fail
Combining with MongoDB operations
await outbox.withScope(async ({ publish, session }) => {
// MongoDB operations using the same session
await db.collection('tasks').updateOne(
{ _id: taskId },
{ $set: { status: 'archived' } },
{ session }
)
// Events published in same transaction
await publish({ type: 'TaskArchived', taskId })
await publish({ type: 'NotificationSent', userId: assigneeId })
})
Return value from withScope
const result = await outbox.withScope(async ({ publish, session }) => {
await publish(event1)
await publish(event2)
return { success: true, count: 2 }
})
console.log(result) // { success: true, count: 2 }
Function type that creates a transaction scope for publishing multiple events atomically.
This method is useful when you need to publish multiple events in a single transaction without repeatedly passing the session parameter.
When to Use
Event - Type of events (use discriminated unions for multiple event types)