Hermes MongoDB
    Preparing search index...

    Type Alias WithScope<Event>Template

    WithScope: (
        scopeFn: (scope: OutboxScope<Event>) => Promise<void>,
    ) => Promise<void>

    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.

    • Publishing multiple related events that should be atomic
    • No business data to save, only events
    • Simplifying code by not passing session explicitly

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

    Type Parameters

    Type Declaration

      • (scopeFn: (scope: OutboxScope<Event>) => Promise<void>): Promise<void>
      • Parameters

        Returns Promise<void>

        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 }