This library provides an event emitter middleware for Hono, allowing you to easily implement and manage event-driven architectures in your Hono applications.
It enables event driven logic flow, allowing you to decouple your code and make it more modular and maintainable.
as [Adonis.js](https://docs.adonisjs.com/guides/emitter), [Nest.js](https://docs.nestjs.com/techniques/events), [Hapi.js](https://github.com/hapijs/podium), [Meteor](https://github.com/Meteor-Community-Packages/Meteor-EventEmitter) and others.
Creates a Hono middleware that adds an event emitter to the context.
```ts
function emitter<EPMapextendsEventPayloadMap>(
eventHandlers?: EventHandlers<EPMap>,
options?: EventEmitterOptions
): MiddlewareHandler
```
#### Parameters
-`eventHandlers` - (optional): An object containing initial event handlers. Each key is event name and value is array of event handlers. Use `defineHandlers` function to create fully typed event handlers.
-`options` - (optional): An object containing options for the emitter. Currently, the only option is `maxHandlers`, which is the maximum number of handlers that can be added to an event. The default is `10`.
#### Returns
A Hono middleware function that adds an `Emitter` instance to the context under the key 'emitter'.
#### Example
```ts
app.use(emitter(eventHandlers));
```
### createEmitter
Creates new instance of event emitter with provided handlers. This is usefull when you want to use the emitter as standalone feature instead of Hono middleware.
```ts
function createEmitter<EPMapextendsEventPayloadMap>(
eventHandlers?: EventHandlers<EPMap>,
options?: EventEmitterOptions
): Emitter<EPMap>
```
#### Parameters
-`eventHandlers` - (optional): An object containing initial event handlers. Each key is event name and value is array of event handlers.
-`options` - (optional): An object containing options for the emitter. Currently, the only option is `maxHandlers`, which is the maximum number of handlers that can be added to an event. The default is `10`.
#### Returns
An `Emitter` instance:
#### Example
```ts
const ee = createEmitter(eventHandlers);
```
### defineHandler
A utility function to define a typed event handler.
```ts
function defineHandler<EPMapextendsEventPayloadMap,KeyextendskeyofEPMap,EextendsEnv =Env>(
handler: EventHandler<EPMap[Key],E>,
): EventHandler<EPMap[Key],E>
```
#### Parameters
-`handler`: The event handler function to be defined.
#### Type parameters
-`EPMap`: The available event key to payload map i.e.: `type AvailableEvents = { 'user:created': { name: string } };`.
-`Key`: The key of the event type.
-`E`: (optional) - The Hono environment, so that the context within the handler has the right info.
#### Returns
The same event handler function with proper type inference.
-`key`: The event key to listen for. Must be a key of `EventHandlerPayloads`.
-`handler`: The function to be called when the event is emitted. If using within a Hono middleware or request handler, do not use anonymous or closure functions!
It should accept two parameters:
-`c`: The current Hono context object.
-`payload`: The payload passed when the event is emitted. The type of the payload is inferred from the `EventHandlerPayloads` type.
#### Returns
`void`
#### Example
Using outside the Hono middleware or request handler:
```ts
type AvailableEvents = {
'user:created': { name: string };
};
const ee = createEmitter<AvailableEvents>();
// If adding event handler outside of Hono middleware or request handler, you can use both, named or anonymous function.
ee.on('user:created', (c, user) => {
console.log('New user created:', user)
})
```
Using within Hono middleware or request handler:
```ts
type AvailableEvents = {
'user:created': { name: string };
};
// Define event handler as named function, outside of the Hono middleware or request handler to prevent duplicates/memory leaks
Synchronously emits an event with the specified key and payload.
#### Signature
```ts
emit<KeyextendskeyofEventPayloadMap>(
c: Context,
key: Key,
payload: EventPayloadMap[Key]
): void
```
#### Parameters
-`c`: The current Hono context object.
-`key`: The event key to emit. Must be a key of `EventPayloadMap`.
-`payload`: The payload to pass to the event handlers. The type of the payload is inferred from the `EventPayloadMap` type.
#### Returns
`void`
#### Example
```ts
app.post('/users', (c) => {
const user = { name: 'Alice' };
c.get('emitter').emit(c, 'user:created', user);
});
```
### emitAsync
Asynchronously emits an event with the specified key and payload.
#### Signature
```ts
emitAsync<KeyextendskeyofEventPayloadMap>(
c: Context,
key: Key,
payload: EventPayloadMap[Key],
options?: EmitAsyncOptions
): Promise<void>
```
#### Parameters
-`c`: The current Hono context object.
-`key`: The event key to emit. Must be a key of `EventPayloadMap`.
-`payload`: The payload to pass to the event handlers. The type of the payload is inferred from the `EventPayloadMap` type.
-`options` (optional): An object containing options for the asynchronous emission.
Currently, the only option is `mode`, which can be `'concurrent'` (default) or `'sequencial'`.
- The `'concurrent'` mode will call all handlers concurrently (at the same time) and resolve or reject (with aggregated errors) after all handlers settle.
- The `'sequencial'` mode will call handlers one by one and resolve when all handlers are done or reject when the first error is thrown, not executing rest of the handlers.
### What the heck is event emitter and why should I use it?
Event emitter is a pattern that allows you to decouple your code and make it more modular and maintainable.
It's a way to implement the observer pattern in your application.
It's especially useful in larger projects or projects with a lot of interactions between features.
Just imagine you have a user registration feature, and you want to send a welcome email after the user is created. You can do this by emitting an event `user:created` and then listen to this event in another part of your application (e.g. email service).
### How is this different to the built-in EventEmitter in Node.js?
The build-in EventEmitter has huge API surface, weak TypeScript support and does only synchronous event emitting. Hono's event emitter is designed to be minimal, lightweight, edge compatible and fully typed. Additionally, it supports async event handlers.
### Is there a way to define event handlers with types?
Yes, you can use `defineHandlers` and `defineHandler` functions to define event handlers with types. This way you can leverage TypeScript's type inference and get better type checking.
### Does it support async event handlers?
Yes, it does. You can use async functions as event handlers and emit the events using `emitAsync` method.
### What happens if I emit an event that has no handlers?
Nothing. The event will be emitted, but no handlers will be called.
### Using `emitAsync` function, what happens if one or more of the handlers reject?
- If using `{ mode = 'concurrent' }` in the options (which is the default), it will call all handlers concurrently (at the same time) and resolve or reject (with aggregated errors) after all handlers settle.
- If using `{ mode = 'sequencial' }` in the options, it will call handlers one by one and resolve when all handlers are done or reject when the first error is thrown, not executing rest of the handlers.
### Is it request scoped?
No, by design it's not request scoped. The same Emitter instance is shared across all requests.
This aproach prevents memory leaks (especially when using closures or dealing with large data structures within the handlers) and additional strain on Javascript garbage collector.
### Why can't I use anonymous functions or closures as event handlers when adding them inside of middleware?
This is because middleware or request handlers run repeatedly on every request, and because anonymous functions are created as new unique object in memory every time,
you would be instructing the event emitter to add new handler for same key every time the request/middleware runs.
Since they are each different objects in memory they can't be checked for equality and would result in memory leaks and duplicate handlers.
You should use named functions if you really want to use the `on()` method inside of middleware or request handler.