Hermes MySQL
    Preparing search index...

    Function createOutboxConsumer

    • Template

      Creates an outbox for MySQL 8.0+ (and Aurora MySQL 3).

      The application stores messages in the hermes_outbox table in its own transactions (queue), and the consumer polls the table and publishes them. It does not keep a position like "the last published position", so a message is not skipped when its transaction commits after a transaction with a greater AUTO_INCREMENT position.

      Many instances of the application can run the consumer. By default (ordering: 'partition'), every partition is published by one instance at a time, in the order of the positions, and the instances share the partitions.

      Delivery is at-least-once, so make the handlers of the messages idempotent, e.g. with the messageId.

      start() polls with its own small pool (createPollingPool), which runs in READ COMMITTED, and stop() closes it. queue() without tx and getDbConnection() create another pool on their first use. stop() does not close it, because the application may still use it, so close it with getDbConnection().end(), or the open connections keep the process running. queue() with tx does not create it.

      Message - The type of the messages

      Type Parameters

      Parameters

      Returns OutboxConsumer<Message>

      import { createOutboxConsumer } from '@chassisjs/hermes-mysql'

      const outbox = createOutboxConsumer<DomainEvent>({
      getOptions: () => ({ host: 'localhost', port: 3306, user: 'app', password: 'secret', database: 'app' }),
      publish: async (envelope) => {
      await broker.publish(envelope.messageType, envelope.message)
      },
      consumerName: 'app',
      })

      const stop = await outbox.start()

      const connection = await pool.getConnection()
      await connection.beginTransaction()
      await connection.query('INSERT INTO patient (id) VALUES (?)', [patientId])
      await outbox.queue(
      { messageId: patientId, messageType: 'PatientRegistered', message: { patientId } },
      { tx: connection, partitionKey: tenantId },
      )
      await connection.commit()