Event Bus
Decouple modules with the @axiljs/events EventBus: typed publish/subscribe, wildcard patterns, once and waitFor, middleware, history and @OnEvent handlers.
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.
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?)
| Option | Type | Default | Description |
|---|---|---|---|
maxListeners | number | 0 (unlimited) | Warn once per event type when more handlers than this are added. The handler is still registered |
onError | (error: Error, event: axilEvent) => void | logs to console.error | Called when a handler throws or rejects |
middleware | EventMiddleware[] | [] | Functions run around every emit, in order, before the handlers |
async | boolean | Declared in EventBusOptions but not read by EventBus; handlers are always awaited | |
transport | EventTransport | none | Carrier to buses in other processes. See Cross-process events (new in 0.3.4) |
broadcast | boolean | false | With a transport, broadcast every emit unless it passes { broadcast: false } |
The event object
Every handler receives an axilEvent<T>:
| Field | Type | Description |
|---|---|---|
type | string | Event type, e.g. 'user.created' |
payload | T | Data passed to emit() |
id | string | Unique ID (crypto.randomUUID()) |
timestamp | string | ISO time the event was emitted |
version | number | Schema version, 1 unless set in meta |
source | string | undefined | Emitting module or service |
correlationId | string | undefined | Ties together events from one request or flow |
causationId | string | undefined | ID 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.
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
onErrorandemit()still resolves.
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.
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:
| Field | Type | Description |
|---|---|---|
id | string | Subscription ID |
eventType | string | The pattern it was registered with |
unsubscribe | () => void | Remove this handler |
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.
| Pattern | Matches | Does not match |
|---|---|---|
user.created | user.created | user.deleted |
user.* | user.created, user.deleted, user.profile.updated | user, users.created |
*.created | user.created, order.created | user.deleted |
* | every event |
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.
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.
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
| Method | Returns |
|---|---|
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.
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.
| Option | Type | Default | Description |
|---|---|---|---|
logger | EventsLogger | false | console | false prints nothing. An object with info(msg) and warn(msg) receives the messages as plain text, prefixed with [AxilJS Events] |
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.
1import { EventBus, getGlobalEventBus, setGlobalEventBus } from '@axiljs/events'
2
3setGlobalEventBus(new EventBus({ maxListeners: 50 }))
4getGlobalEventBus().emit('app.started', { pid: process.pid })Testing
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})Related
- Cross-process events
- Messaging decorators
- Queue
- Request context: a source of
correlationIdvalues - Server-Sent Events: push bus events to browsers
- Assertions
Was this page helpful?