Events
Events let one part of your application announce that something happened without knowing who reacts to it. Megh's event system is typed, supports synchronous, delayed and queued delivery, and can broadcast over Socket.IO.
Events stay in the process that dispatches them, unless you mark them with @DistributedEvent. Then they travel to every replica and service over messaging. See Distributed events.
Generate them
npx megh make:event UserCreated and npx megh make:listener SendWelcomeEmail --event UserCreated write both files. See Generators.
Defining an event
An event extends MeghEvent<TPayload>. The payload type is yours; the base class fills in name and timestamp.
import { MeghEvent } from '@meghjs/core';
export type UserCreatedPayload = {
userId: number;
name: string;
};
export class UserCreatedEvent extends MeghEvent<UserCreatedPayload> {}Defining a listener
A listener extends MeghEventListener<TEvent> and implements handler. It may be synchronous or return a promise.
import { MeghEventListener } from '@meghjs/core';
import { UserCreatedEvent } from '../events/user-created.event';
export class UserCreatedListener extends MeghEventListener<UserCreatedEvent> {
async handler(event: UserCreatedEvent): Promise<void> {
console.log(`User created → id=${event.payload.userId}, name=${event.payload.name}`);
}
}Registering listeners
The simplest way is @Listener. The class is resolved through dependency injection, so it can inject services, and it is registered when the app runs:
import { Listener, MeghEventListener } from '@meghjs/core';
import { UserCreatedEvent } from '../events/user-created.event';
import { MailService } from '../services/mail.service';
@Listener(UserCreatedEvent)
export class UserCreatedListener extends MeghEventListener<UserCreatedEvent> {
constructor(private readonly mail: MailService) {
super();
}
async handler(event: UserCreatedEvent): Promise<void> {
await this.mail.welcome(event.payload.userId);
}
}@Listener classes start in app.run(), so they don't run in a script that never calls it.
By hand
EventRegistry is a singleton. Register listeners on it once during app setup.
import { EventRegistry } from '@meghjs/core';
import { UserCreatedEvent } from './events/user-created.event';
import { UserCreatedListener } from './listeners/user-created.listener';
const registry = EventRegistry.getInstance();
registry.register(UserCreatedEvent, new UserCreatedListener());An event may have several listeners — they run in registration order.
Use once for a listener that should fire a single time and then be discarded:
registry.once(UserCreatedEvent, {
handler(event: UserCreatedEvent) {
console.log(`Sending welcome email to ${event.payload.name}`);
},
});Dispatching
import { AppService, EventDispatcher } from '@meghjs/core';
import { UserCreatedEvent } from '../events/user-created.event';
@AppService
export class UserService {
private readonly dispatcher = new EventDispatcher();
async create(name: string) {
const userId = 1; // ...persist the user
await this.dispatcher.dispatch(new UserCreatedEvent({ userId, name }));
return { userId, name };
}
}By default listeners run synchronously, in the current tick, before dispatch resolves.
Queued delivery
Pass queue: true to hand the event to the in-memory queue instead. Listener failures are then retried:
await dispatcher.dispatch(new UserCreatedEvent({ userId: 1, name: 'Tareq' }), {
queue: true,
retry: 3,
retryDelay: 500, // milliseconds between attempts
});retry and retryDelay are only accepted together with queue: true.
Jobs that still fail after their last retry are kept, up to 1000 of them, and logged:
import { EventQueue } from '@meghjs/core';
const queue = EventQueue.getInstance();
const failed = queue.getFailedJobs(); // FailedEventJob[]
queue.clearFailed();
await queue.whenIdle(); // useful in testsDelayed delivery
delay takes milliseconds or a duration string: '500ms', '5s', '2m', '1h', '1d'. It also works together with queue: true.
await dispatcher.dispatch(new UserCreatedEvent({ userId: 1, name: 'Tareq' }), {
delay: '5s', // fire listeners 5 seconds from now
});Broadcasting
Add a broadcast option to forward the event to Socket.IO as well as to the local listeners. Clients receive { name, payload } on the channel:
await dispatcher.dispatch(event, {
broadcast: { type: 'socket', channel: 'user:create', room: 'admins' },
});Socket broadcast needs app.useSocketIo(). Without it, dispatch rejects and the local listeners do not run.
type: 'socket' is the only broadcast type. Broadcasting is for browsers; to reach other servers, use a distributed event.
INFO
A listener that throws is logged and does not stop the other listeners for that event. With queue: true, the failure is retried according to retry.
Listener registry
- Listeners are keyed by the event class, so two event classes with the same name do not collide.
oncelisteners fire exactly once, even when the event is dispatched concurrently.registry.getListeners(UserCreatedEvent)takes the class or an event instance.registry.clear(UserCreatedEvent)removes its listeners, andregistry.clear()removes all of them.
Distributed events
Mark an event with @DistributedEvent and dispatch() publishes it on the messaging transport. @Listener classes receive it in whichever replica or service picks it up:
import { DistributedEvent, Listener, MeghEvent, MeghEventListener } from '@meghjs/core';
@DistributedEvent('user.created')
export class UserCreatedEvent extends MeghEvent<UserCreatedPayload> {}
@Listener(UserCreatedEvent, { group: 'mail', retry: { retries: 5 } })
export class SendWelcomeMail extends MeghEventListener<UserCreatedEvent> {
async handler(event: UserCreatedEvent) {
// runs once per event, on one replica in the "mail" group
}
}- Every listener group receives each event once. Replicas in one group share the work.
- A failing listener is retried with backoff, then dead-lettered. Delivery is at least once, with dedupe by message ID.
delayworks as for local events.queue,retryandretryDelayonly apply to listeners registered by hand in this process.- Inside a database transaction, with the outbox on, the event is published only after the transaction commits. Pass
outbox: falseto publish at once, oroutbox: trueto store it in the outbox outside a transaction too.
With no transport configured, distributed events use the in-process memory transport, so they work in development without a broker. See Messaging for transports, groups, retries and the outbox.