@freshpointcz/fresh-messenger
v0.0.1
Published
Utilized implementation for broadcasting, publishing and consuming messages across micro-services.
Downloads
130
Keywords
Readme
@freshpointcz/fresh-messenger 🚀
A high-reliability, opinionated RabbitMQ messaging client built specifically for the internal microservices ecosystem.
This package abstracts away the complexities of AMQP topology, providing a dead-simple API for Publishing and Subscribing to domain events while guaranteeing message delivery, automatic DLQ routing, and payload validation.
✨ Key Features
- Zero Message Loss: Publishers use
ConfirmChannelsto await explicit broker ACKs before resolving. - Auto-Provisioned DLQs: Subscribers automatically create their own
[serviceName].dlqand handlenackrouting on errors. - Competing Consumers: Simply provide your
serviceNameand RabbitMQ will automatically load-balance messages across your deployed replicas. - Payload Guardrails: Built-in size limits (Warning at 512KB, Rejection at 1MB) to protect broker memory.
- Standardized Envelopes: All messages are automatically wrapped with UUIDs and ISO timestamps.
📦 Installation
Install the package alongside its dependencies, amqplib & @types/amqplib.
npm install @freshpointcz/fresh-messenger🚀 Quick Start: The Messenger Facade
The Messenger class is a Static Singleton designed to act as your microservice's central hub for all RabbitMQ traffic.
1. Initialization & Subscribing (App Startup)
In your application's entry point (e.g., server.ts or main.ts), initialize the Messenger and define your central routing logic. This acts as the single source of truth for the events this service consumes.
import { Messenger } from "@freshpointcz/fresh-messenger";
async function bootstrap() {
// 1. Initialize the connection (URL can be a string or a credentials object)
await Messenger.initialize(
process.env.RABBIT_URL || "amqp://localhost:5672",
"pricing-service" // This names your queue: pricing-service.events
);
// 2. Define topics and start the central event dispatcher
const topics = ["product.created", "product.updated"];
await Messenger.startSubscribing(topics, async (event, msg) => {
const routingKey = msg.fields.routingKey;
// Route the event to the appropriate domain logic
switch (routingKey) {
case "product.created":
console.log("New product created:", event.payload);
break;
case "product.updated":
console.log("Product updated:", event.payload);
break;
default:
console.warn(`[Router] Unhandled routing key: ${routingKey}`);
}
});
console.log("Pricing service is listening for events!");
}
bootstrap();
Note: If your routing logic throws an error, the Messenger automatically catches it and safely routes the message to your pricing-service.dlq.
2. Publishing Events (Anywhere in the App)
Because Messenger safely holds the connection state, you can import it anywhere in your codebase to publish events without passing instances around.
// controllers/order-controller.ts
import { Messenger } from "@freshpointcz/fresh-messenger";
export async function processOrder(req, res) {
const orderData = req.body;
// ... Save to Database ...
// Publish the event (awaits safe confirmation from RabbitMQ)
await Messenger.publisher.publish("order.paid", orderData);
res.status(201).send("Order Processed");
}🛑 Graceful Shutdown
To prevent memory leaks and ensure active messages finish processing before your container dies, always hook the disconnectAll() method into your application's termination signals.
// app.ts
process.on("SIGINT", async () => {
console.log("Shutting down messaging connections...");
await Messenger.disconnectAll();
process.exit(0);
});🛠️ Advanced Usage
The Messenger facade covers 99% of use cases. However, if you are building an edge-case service that requires multiple distinct connections or needs to connect to a different exchange, the underlying Publisher and Subscriber classes are still exported and available for manual instantiation.
