greenwebsites-event-dispatcher
v1.0.6
Published
A simple event dispatcher for sending structured events
Maintainers
Readme
🚀 Event Dispatcher
A lightweight Node.js package for dispatching structured events to a middleware API.
📌 Features
✅ Standardized event format with metadata
✅ Automatic eventId and correlationId generation
✅ Lightweight, few dependencies (only uses uuid jest)
✅ Works with any HTTP-based middleware API
🛠 Installation
Install via npm:
npm install greenwebsites-event-dispatcher 📌 Usage
1️⃣ Import and Initialize the Dispatcher
import { EventDispatcher } from "greenwebsites-event-dispatcher";
// Initialize with middleware URL from .env or provide a URL
const dispatcher = new EventDispatcher();2️⃣ Sending an Event
async function sendEvent() {
await dispatcher.sendEvent("user-service", "UserSignedUp", {
userId: "12345",
email: "[email protected]",
});
}
sendEvent().catch(console.error);3️⃣ Sending an Event with Correlation ID
async function sendWithCorrelation() {
await dispatcher.sendEvent("billing-service", "InvoiceGenerated", {
invoiceId: "INV-5678",
amount: 150.00,
status: "pending",
}, "req-98765"); // Correlation ID for tracking
}
sendWithCorrelation().catch(console.error);📌 Error Handling & Retries
If the middleware is unreachable, the dispatcher will log the error.
To implement retry logic, wrap it in a function like this:
async function sendWithRetries(dispatcher, source, type, detail, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
await dispatcher.sendEvent(source, type, detail);
return;
} catch (error) {
console.error(`Attempt ${i + 1} failed. Retrying...`);
if (i === retries - 1) throw error;
await new Promise(resolve => setTimeout(resolve, (i + 1) * 1000));
}
}
}📌 Example Scripts
You can run example scripts included in the package:
- Send a test event
npm run example:send - Send with a correlation ID
npm run example:correlation - Test error handling
npm run example:failure
🛠 Development
1️⃣ Clone the Repository
git clone https://github.com/yourusername/event-dispatcher.git
cd event-dispatcher
npm install2️⃣ Running Tests
npm test3️⃣ Building the Project
npm run build📌 Contributing
We welcome contributions! To contribute:
- Fork the repo and create a new branch.
- Make your changes and add tests.
- Open a pull request.
📌 License
📜 This package is MIT licensed.
