clean-nodejs-rabbitmq
v1.0.0
Published
A clean RabbitMQ service module for Node.js with TypeScript support
Maintainers
Readme
RabbitMQ Service Module
A clean, TypeScript-based RabbitMQ service module for Node.js applications. This module provides a simple and configurable way to integrate RabbitMQ messaging into your applications.
Features
- 🚀 Easy to use API with async/await support
- 🔧 Hybrid configuration (environment variables + explicit config)
- 📝 Full TypeScript support with exported types
- 🛡️ Robust error handling with custom error classes
- 📊 Integrated logging with Winston
- 🎯 Event bus implementation for domain events
- 🔄 Connection retry logic with configurable attempts
Installation
npm install clean-nodejs-rabbitmqQuick Start
Basic Usage
import { RabbitMQService, RabbitMQAdapter, createRabbitMQConfig } from 'clean-nodejs-rabbitmq';
// Initialize with default config (uses env vars or defaults)
const service = await RabbitMQService.init();
// Or with custom config
const service = await RabbitMQService.init(createRabbitMQConfig({
uri: 'amqp://localhost:5672',
serviceName: 'my-service'
}));
// Create adapter for messaging
const messaging = new RabbitMQAdapter(service);
// Publish a message
await messaging.publish('my-exchange', 'my.routing.key', {
eventType: 'UserCreated',
payload: { userId: 123, name: 'John Doe' }
});
// Consume messages
await messaging.consume('my-queue', async (message) => {
console.log('Received:', message);
// Process message...
});Event Bus Usage
import { RabbitMQEventBus } from 'clean-nodejs-rabbitmq';
const eventBus = new RabbitMQEventBus(messaging);
// Subscribe to events
await eventBus.subscribe('UserCreated', async (event) => {
console.log('User created:', event);
});
// Publish domain events
await eventBus.publish({
userId: 123,
name: 'John Doe',
eventType: 'UserCreated'
});Configuration
The module supports hybrid configuration - you can use environment variables, explicit configuration, or a combination of both.
Environment Variables
export RABBITMQ_URI=amqp://localhost:5672
export SERVICE_NAME=my-service
export RABBITMQ_RETRY_ATTEMPTS=5
export RABBITMQ_RETRY_DELAY=3000
export RABBITMQ_EXCHANGE_NAME=domain-eventsExplicit Configuration
import { createRabbitMQConfig } from 'clean-nodejs-rabbitmq';
const config = createRabbitMQConfig({
uri: 'amqp://localhost:5672',
serviceName: 'my-service',
retryAttempts: 5,
retryDelay: 3000,
exchangeName: 'my-exchange'
});Default Configuration
{
uri: 'amqp://localhost:5672',
serviceName: 'default-service',
retryAttempts: 10,
retryDelay: 5000,
exchangeName: 'domain-events'
}API Reference
RabbitMQService
Main service class for RabbitMQ operations.
class RabbitMQService {
static async init(config?: Partial<RabbitMQModuleConfig>): Promise<RabbitMQService>
}RabbitMQAdapter
Adapter implementing IMessagingService interface.
class RabbitMQAdapter implements IMessagingService {
constructor(service: RabbitMQService);
async publish(exchange: string, routingKey: string, message: Message): Promise<void>;
async consume(queue: string, handler: (message: Message) => Promise<void>): Promise<void>;
async bindQueue(queue: string, exchange: string, routingKey: string): Promise<void>;
}RabbitMQEventBus
Event bus implementation for domain events.
class RabbitMQEventBus implements IEventBus {
constructor(messagingService: IMessagingService);
async publish(event: any): Promise<void>;
async subscribe(eventType: string, handler: Function): Promise<void>;
}Error Handling
The module provides specific error classes for different failure scenarios:
RabbitMQConnectionError: Connection failuresRabbitMQChannelError: Channel initialization issuesRabbitMQPublishError: Publishing failuresRabbitMQConsumeError: Consumption failuresRabbitMQUriValidationError: Invalid URI formatRabbitMQTimeoutError: Timeout errors
import { RabbitMQService, RabbitMQConnectionError } from 'clean-nodejs-rabbitmq';
try {
const service = await RabbitMQService.init();
} catch (error) {
if (error instanceof RabbitMQConnectionError) {
console.error('Failed to connect to RabbitMQ:', error.message);
}
}Logging
The module includes integrated logging using Winston. Logs include service name and relevant context.
Configure logging level via environment:
export NODE_ENV=production # info level
# or development for debug levelDevelopment
# Install dependencies
npm install
# Build
npm run build
# Development with watch
npm run dev
# Run tests
npm testLicense
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
