Template
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()
Creates an outbox for MySQL 8.0+ (and Aurora MySQL 3).
The application stores messages in the
hermes_outboxtable 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 greaterAUTO_INCREMENTposition.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 inREAD COMMITTED, andstop()closes it.queue()withouttxandgetDbConnection()create another pool on their first use.stop()does not close it, because the application may still use it, so close it withgetDbConnection().end(), or the open connections keep the process running.queue()withtxdoes not create it.Message - The type of the messages