Events & Event Bus¶
Katal includes a zero-dependency In-Memory Event Bus that decouples domain actions (e.g. user registrations, order payments, audit trails) from secondary side-effects (e.g. sending transactional emails, publishing webhooks, cache invalidation).
1. Quick Start¶
import { Application } from "katal";
const app = new Application({ port: 3000 });
// 1. Listen for an event (async listener)
app.on<{ orderId: string; amount: number }>("order.placed", async (order) => {
console.log(`Processing receipt for Order #${order.orderId} ($${order.amount})`);
await sendReceiptEmail(order);
});
// 2. Listen only once
app.once("app.booted", () => {
console.log("Database connections verified and application ready.");
});
// 3. Emit asynchronously (awaits all registered listeners)
await app.emit("order.placed", {
orderId: "ord-9821",
amount: 149.99,
});
// 4. Emit synchronously (strict synchronous execution)
app.emitSync("audit.logged", { action: "login", userId: "u-1" });
2. Strongly-Typed Event Map Pattern¶
To enforce compile-time type safety across your entire event architecture, define a centralized AppEvents type map:
// types/events.ts
export interface AppEvents {
"user.registered": {
userId: string;
email: string;
registeredAt: Date;
};
"invoice.paid": {
invoiceId: string;
customerId: string;
amountCents: number;
};
"security.alert": {
severity: "low" | "medium" | "high" | "critical";
ip: string;
description: string;
};
}
Type-Safe TypedEventBus Wrapper¶
import { EventBus } from "katal";
import type { AppEvents } from "./types/events";
export class TypedEventBus {
constructor(private readonly bus: EventBus) {}
on<K extends keyof AppEvents>(
event: K,
listener: (payload: AppEvents[K]) => void | Promise<void>
): this {
this.bus.on(event as string, listener);
return this;
}
async emit<K extends keyof AppEvents>(
event: K,
payload: AppEvents[K]
): Promise<void> {
await this.bus.emit(event as string, payload);
}
}
// Bind to IoC container
app.singleton(TypedEventBus, (c) => new TypedEventBus(c.resolve("events")));
3. Emitting Domain Events from Controllers¶
Keep controllers lean by dispatching domain events rather than embedding third-party notification logic:
import { Controller } from "katal";
import type { RequestContext } from "katal";
import { EventBus } from "katal";
export class RegisterUserController extends Controller {
constructor(
private readonly events: EventBus,
private readonly userRepo: UserRepository
) {
super();
}
async handle(ctx: RequestContext) {
const { email, name } = ctx.body as { email: string; name: string };
// 1. Persist user in database
const user = await this.userRepo.create({ email, name });
// 2. Dispatch event to decouple secondary concerns
await this.events.emit("user.registered", {
userId: user.id,
email: user.email,
registeredAt: new Date(),
});
// 3. Return immediate HTTP 201 response
return this.created({ id: user.id, email: user.email });
}
}
4. emit() vs emitSync()¶
| Method | Behavior | When to Use |
|---|---|---|
await app.emit(event, payload) |
Executes listeners sequentially in order of registration, awaiting any returned Promise. |
Recommended default. Used for network calls, queue dispatches, and async database logging. |
app.emitSync(event, payload) |
Runs listeners in standard synchronous execution. Throws an Error if any listener returns a Promise. |
Strictly synchronous operations (in-memory counters, telemetry timestamps, metric counters). |
5. Event Listener Management¶
Remove Listeners¶
const handler = (payload: any) => console.log(payload);
// Add listener
app.on("metrics.tick", handler);
// Remove specific listener
app.off("metrics.tick", handler);
// Remove ALL listeners for an event
app.off("metrics.tick");
Inspect and Reset¶
const count = app.resolve<EventBus>("events").listenerCount("user.registered");
console.log(`Active listeners: ${count}`);
// Clear all events in test suites
app.resolve<EventBus>("events").clear();
6. Testing Events in In-Memory Test Suites¶
Because Katal executes in memory, you can assert event dispatch without configuring external message brokers:
import { describe, it, expect } from "bun:test";
import { Application } from "katal";
import { RegisterUserController } from "./RegisterUserController";
describe("RegisterUserController Event Emission", () => {
it("dispatches user.registered event upon successful creation", async () => {
const app = new Application();
let emittedPayload: any = null;
app.on("user.registered", (payload) => {
emittedPayload = payload;
});
const res = await app.handle(new Request("http://localhost/api/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: "jane@example.com", name: "Jane" }),
}));
expect(res.status).toBe(201);
expect(emittedPayload).not.toBeNull();
expect(emittedPayload.email).toBe("jane@example.com");
});
});