TemplateSingle event or array of events to publish
OptionalsessionOrCallback: ClientSession | SaveWithEventCallbackOptional session or callback for transactional consistency
Promise that resolves when event(s) are committed to outbox collection
Publish with business logic (recommended)
await outbox.publish(medicineAssignedEvent, async (session, db) => {
// Business logic in same transaction
await db.collection('assignments').insertOne({
patientId: 'patient-123',
medicineId: 'med-456',
assignedAt: new Date()
}, { session })
})
// Either both succeed or both fail - no inconsistency possible
Publish with existing session
await client.withSession(async (session) => {
await session.withTransaction(async (session) => {
// Business operations
await db.collection('tasks').updateOne(
{ _id: taskId },
{ $set: { status: 'completed' } },
{ session }
)
// Publish event in same transaction
await outbox.publish({
type: 'TaskCompleted',
taskId,
completedAt: new Date()
}, session)
})
})
Publish without transaction (auto-transaction)
// Hermes creates transaction automatically
await outbox.publish({
type: 'NotificationSent',
userId: 'user-123'
})
// Event inserted in its own transaction
Publish multiple events
await outbox.publish([
{ type: 'OrderCreated', orderId: '1' },
{ type: 'InvoiceGenerated', invoiceId: '1' }
], async (session, db) => {
await db.collection('orders').insertOne(order, { session })
})
Function type for publishing events to the outbox with transactional consistency.
This function queues events to the outbox collection. Events are inserted into MongoDB and will be streamed via Change Streams to the consumer's
publishcallback.Usage Patterns
Event - Type of events (use discriminated unions for multiple event types)