fastify-event-emitter
v0.2.0
Published
Fastify plugin that exposes a Node.js EventEmitter on the Fastify instance (and optionally on requests).
Maintainers
Readme
fastify-event-emitter
Fastify plugin that exposes a Node.js EventEmitter on the Fastify instance (and optionally on each request).
Features
- Adds an
EventEmitterinstance to your Fastify instance (fastify.eventsby default). - Optionally expose the same emitter on requests (e.g.
request.events) withdecorateRequest: true. - Accept your own
EventEmitterinstance via options. - Lightweight and typed for TypeScript.
Install
npm install fastify-event-emitter
# also install fastify in your project
npm install fastifyUsage
import Fastify from 'fastify';
import fastifyEventEmitter from 'fastify-event-emitter';
const app = Fastify();
// default usage — instance gets `events`
await app.register(fastifyEventEmitter);
// listen
app.events.on('user:created', (user) => {
console.log('user created', user);
});
// emit somewhere in your code
app.events.emit('user:created', { id: 1, name: 'Alice' });Options
| Option | Type | Default | Description |
|----------------------|-------------|----------|-------------|
| emitter | EventEmitter | new EventEmitter() | Provide your own instance |
| decorateKey | string | "events" | The property name for Fastify decorations |
| decorateRequest | boolean | false | Also expose the emitter on request |
| autoRemoveListeners| boolean | false | Automatically remove all listeners when the Fastify instance closes |
Example with auto-cleanup and custom key
import fastifyEventEmitter from 'fastify-event-emitter';
await app.register(fastifyEventEmitter<'bus'>, {
decorateKey: 'bus',
autoRemoveListeners: true,
});
app.bus.on('ready', () => console.log('Bus ready!'));
Example
import Fastify from 'fastify';
import fastifyEventEmitter from 'fastify-event-emitter';
const app = Fastify();
await app.register(fastifyEventEmitter, {
autoRemoveListeners: true,
});
app.events.on('data', console.log);
app.listen({ port: 3000 });
// later...
await app.close(); // 🔥 automatically removes all listenersExample with request decoration:
await app.register(fastifyEventEmitter, { decorateRequest: true });
app.get('/', (request, reply) => {
request.events.emit('hit', { path: request.raw.url });
reply.send({ ok: true });
});💡 Type Augmentation Guide (for custom decorateKey)
TypeScript can't automatically know what property you chose for decorateKey. To fix that, augment the Fastify types in your project:
Create a file like fastify-event-emitter.d.ts
import 'fastify';
import { EventEmitter } from 'events';
declare module 'fastify' {
interface FastifyInstance {
bus: EventEmitter; // 👈 replace `bus` with your custom decorateKey
}
interface FastifyRequest {
bus: EventEmitter;
}
}Then include that file in your tsconfig.json:
{
"include": ["src", "fastify-event-emitter.d.ts"]
}Now TypeScript knows your custom decorated property is an EventEmitter.
