Real-Time

Event Bus

Decouple modules with the @axiljs/events EventBus: typed publish/subscribe, wildcard patterns, once and waitFor, middleware, history and @OnEvent handlers.

7 min readUpdated DocumentationEdit this page
On this page17

@axiljs/events is an in-process publish/subscribe bus. One module emits user.created; any number of others react to it, without importing each other. Handlers can be plain functions or methods marked with @OnEvent(). Patterns with * subscribe to many event types at once.

❯npm install @axiljs/events
❯pnpm add @axiljs/events
❯yarn add @axiljs/events
❯bun add @axiljs/events
TypeScript
TS
1import { EventBus } from '@axiljs/events'
2
3const bus = new EventBus()
4
5bus.on<{ id: number; email: string }>('user.created', async (event) => {
6  await sendWelcomeEmail(event.payload.email)
7})
8
9await bus.emit('user.created', { id: 1, email: 'ada@example.com' })

The bus lives in one process. Events do not cross workers or instances unless you attach a transport and emit with { broadcast: true }; see Cross-process events. For delivery that must be guaranteed or must reach other servers, use a queue.

new EventBus(options?)

OptionTypeDefaultDescription
maxListenersnumber0 (unlimited)Warn once per event type when more handlers than this are added. The handler is still registered
onError(error: Error, event: axilEvent) => voidlogs to console.errorCalled when a handler throws or rejects
middlewareEventMiddleware[][]Functions run around every emit, in order, before the handlers
asyncbooleanDeclared in EventBusOptions but not read by EventBus; handlers are always awaited
transportEventTransportnoneCarrier to buses in other processes. See Cross-process events (new in 0.3.4)
broadcastbooleanfalseWith a transport, broadcast every emit unless it passes { broadcast: false }

The event object

Every handler receives an axilEvent<T>:

FieldTypeDescription
typestringEvent type, e.g. 'user.created'
payloadTData passed to emit()
idstringUnique ID (crypto.randomUUID())
timestampstringISO time the event was emitted
versionnumberSchema version, 1 unless set in meta
sourcestring | undefinedEmitting module or service
correlationIdstring | undefinedTies together events from one request or flow
causationIdstring | undefinedID of the event that caused this one

Publishing

emit(type, payload, meta?)

Builds the event, records it in history, then runs middleware and every matching handler. It resolves when all handlers have finished.

TypeScript
TS
1await bus.emit(
2  'order.placed',
3  { orderId: 'o_1', total: 4200 },
4  { source: 'checkout', correlationId: req.locals.requestId }
5)

meta accepts source, correlationId, causationId and version, plus broadcast for cross-process delivery.

  • Matching handlers run concurrently (Promise.all), not one after another.
  • A handler that throws does not stop the others. The error goes to onError and emit() still resolves.
TypeScript
TS
const bus = new EventBus({
  onError: (error, event) => log.error('event handler failed', { type: event.type, error: error.message })
})

emitMany(events)

Emits a list of { type, payload, meta? } objects and resolves when all of them are done. Each one goes through emit(), and the emits run concurrently. It is a convenience, not a transaction: nothing is rolled back if a handler fails.

TypeScript
TS
1await bus.emitMany([
2  { type: 'stock.reserved', payload: { sku: 'A1', qty: 2 } },
3  { type: 'invoice.created', payload: { orderId: 'o_1' } }
4])

Subscribing

on(pattern, handler)

Registers a handler and returns a Subscription:

FieldTypeDescription
idstringSubscription ID
eventTypestringThe pattern it was registered with
unsubscribe() => voidRemove this handler
TypeScript
TS
1const sub = bus.on('cart.updated', (event) => cache.delete(event.payload.cartId))
2sub.unsubscribe()
3
4// same thing, by ID
5bus.off('cart.updated', sub.id)

Wildcards

A pattern matches when it equals the type, when it is *, or when it matches with each * standing for any run of characters, dots included. Other characters, including ., + and ?, are matched literally.

PatternMatchesDoes not match
user.createduser.createduser.deleted
user.*user.created, user.deleted, user.profile.updateduser, users.created
*.createduser.created, order.createduser.deleted
*every event
TypeScript
TS
bus.on('user.*', (event) => audit.write(event.type, event.payload))
bus.on('*', (event) => metrics.inc(event.type))

once(pattern, handler)

Like on(), but the handler runs a single time and then unsubscribes, even when several emits race.

waitFor(pattern, timeoutMs?)

Returns a Promise of the next matching event. It rejects with Timeout waiting for event: '<pattern>' after timeoutMs (default 30000) and removes its subscription.

TypeScript
TS
const event = await bus.waitFor<{ ok: boolean }>('payment.confirmed', 5000)

Middleware

Middleware runs once per emit, in registration order, around all the handlers. Call next() to continue; skip it to drop the event.

TypeScript
TS
1import { EventBus, type EventMiddleware } from '@axiljs/events'
2
3const timing: EventMiddleware = async (event, next) => {
4  const start = Date.now()
5  await next()
6  log.debug('event handled', { type: event.type, ms: Date.now() - start })
7}
8
9const dropInternal: EventMiddleware = async (event, next) => {
10  if (event.type.startsWith('internal.')) return   // handlers never run
11  await next()
12}
13
14const bus = new EventBus({ middleware: [timing, dropInternal] })

Middleware only runs when at least one handler matches the event.

History and introspection

MethodReturns
getHistory(type?)Copy of recent events, optionally filtered by exact type. Keeps the last 1,000 events, including ones no handler matched
getEventTypes()Patterns that have handlers registered
getHandlerCount(pattern)Handlers registered under exactly that pattern. Wildcard subscribers that would also match are not counted
setMaxListeners(n) / getMaxListeners()Change or read the leak-warning threshold. setMaxListeners returns the bus
clear()Remove all handlers, history and leak warnings. Useful between tests

The leak warning mirrors Node's EventEmitter: it is printed once per pattern with console.warn, and the handler is still added.

Decorator handlers

@OnEvent(pattern) marks a method as a handler. registerEventHandlers(instance, bus, options?) subscribes every marked method on that instance, bound to it. It works with both legacy (experimentalDecorators) and standard TC39 decorators, needs no reflect-metadata, and includes handlers inherited from a parent class.

TypeScript
TS
1import { EventBus, OnEvent, registerEventHandlers, type axilEvent } from '@axiljs/events'
2
3class Notifications {
4  constructor(private mailer: Mailer) {}
5
6  @OnEvent('user.created')
7  async sendWelcome(event: axilEvent<{ email: string }>) {
8    await this.mailer.send(event.payload.email, 'Welcome!')
9  }
10
11  @OnEvent('order.*')
12  async orderActivity(event: axilEvent) {
13    // ...
14  }
15}
16
17const bus = new EventBus()
18registerEventHandlers(new Notifications(mailer), bus)

Registration logging

By default each registration is printed to the console (Registered: Notifications.sendWelcome → 'user.created'), and a decorated name that is not a function is skipped with a console warning.

OptionTypeDefaultDescription
loggerEventsLogger | falseconsolefalse prints nothing. An object with info(msg) and warn(msg) receives the messages as plain text, prefixed with [AxilJS Events]
TypeScript
TS
1registerEventHandlers(new Notifications(mailer), bus, { logger: false })          // silent, e.g. in tests
2
3registerEventHandlers(new Notifications(mailer), bus, {
4  logger: { info: (m) => log.info(m), warn: (m) => log.warn(m) }
5})

Global bus

getGlobalEventBus() returns a process-wide EventBus, created on first call. setGlobalEventBus(bus) replaces it, for example with a bus that has your onError and middleware, or with a fresh bus in each test.

TypeScript
TS
1import { EventBus, getGlobalEventBus, setGlobalEventBus } from '@axiljs/events'
2
3setGlobalEventBus(new EventBus({ maxListeners: 50 }))
4getGlobalEventBus().emit('app.started', { pid: process.pid })

Testing

TypeScript
TS
1import { describe, it, expect, beforeEach } from '@axiljs/testing'
2import { EventBus } from '@axiljs/events'
3
4describe('checkout', () => {
5  let bus: EventBus
6  beforeEach(() => { bus = new EventBus() })
7
8  it('emits order.placed', async () => {
9    const placed = bus.waitFor('order.placed', 1000)
10    await checkout(bus, { sku: 'A1' })
11    expect((await placed).payload).toMatchObject({ sku: 'A1' })
12  })
13})

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY