Hermes MongoDB
    Preparing search index...

    Type Alias Publish<Event>Template

    Publish: (
        event: Event | Event[],
        sessionOrCallback?: ClientSession | SaveWithEventCallback,
    ) => Promise<void>

    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 publish callback.

    1. With callback - Publish event with business logic in same transaction
    2. With session - Use existing MongoDB session
    3. Without transaction - Creates new transaction automatically

    Event - Type of events (use discriminated unions for multiple event types)

    Type Parameters

    • Event

    Type Declaration

      • (
            event: Event | Event[],
            sessionOrCallback?: ClientSession | SaveWithEventCallback,
        ): Promise<void>
      • Parameters

        • event: Event | Event[]

          Single event or array of events to publish

        • OptionalsessionOrCallback: ClientSession | SaveWithEventCallback

          Optional session or callback for transactional consistency

        Returns Promise<void>

        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 })
    })