{"_id":"@bvhoach2393/nest-rabbitmq","_rev":"2-3c560bd5eded5205fb458ff489daea75","name":"@bvhoach2393/nest-rabbitmq","dist-tags":{"latest":"1.0.4"},"versions":{"1.0.3":{"name":"@bvhoach2393/nest-rabbitmq","version":"1.0.3","keywords":["nestjs","rabbitmq","message-queue","amqp","consumer","producer"],"author":{"name":"bvhoach2393"},"license":"MIT","_id":"@bvhoach2393/nest-rabbitmq@1.0.3","maintainers":[{"name":"bvhoach2393","email":"bvhoach2393@gmail.com"}],"homepage":"https://github.com/bvhoach2393/nest-rabbitmq#readme","bugs":{"url":"https://github.com/bvhoach2393/nest-rabbitmq/issues"},"dist":{"shasum":"24340bb70f29494b2007adeb769951427d50fd3a","tarball":"https://registry.npmjs.org/@bvhoach2393/nest-rabbitmq/-/nest-rabbitmq-1.0.3.tgz","fileCount":4,"integrity":"sha512-VtXue43vqctPSkoaG+0hQtT4NcxS8dW9Wqav/Cv2q5rgF8aDvTfyKOL49RufXtCHqmmiOGjSBg2EhNgdg5lTKg==","signatures":[{"sig":"MEUCIQDzg/nbfygSvctmUmbyBQCl4pjzUeM4Ncu3g73iH0J5owIgEWzaV08qE8h7xYovY9RJt55sbcg1gfhK6pp7VvdLtTE=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":13858},"main":"index.js","types":"index.d.ts","gitHead":"b95699478e63d384f0a54294129a6b0af82d688e","scripts":{"test":"jest","build":"tsc","test:watch":"jest --watch","prepublishOnly":"npm run build"},"_npmUser":{"name":"bvhoach2393","email":"bvhoach2393@gmail.com"},"repository":{"url":"git+https://github.com/bvhoach2393/nest-rabbitmq.git","type":"git"},"_npmVersion":"11.4.2","description":"NestJS RabbitMQ library for handling message queues with consumer and producer services","directories":{},"_nodeVersion":"24.2.0","publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.0.0","typescript":"^5.0.0","@types/jest":"^29.0.0","@types/amqplib":"^0.10.5"},"peerDependencies":{"rxjs":"^7.8.0","amqplib":"^0.10.0","@nestjs/core":"^11.0.0","@nestjs/common":"^11.0.0","@nestjs/config":"^4.0.0","reflect-metadata":"^0.2.0"},"_npmOperationalInternal":{"tmp":"tmp/nest-rabbitmq_1.0.3_1752755828723_0.11968222579200938","host":"s3://npm-registry-packages-npm-production"}},"1.0.4":{"name":"@bvhoach2393/nest-rabbitmq","version":"1.0.4","description":"NestJS RabbitMQ library for handling message queues with consumer and producer services","main":"index.js","types":"index.d.ts","author":{"name":"bvhoach2393"},"license":"MIT","keywords":["nestjs","rabbitmq","message-queue","amqp","consumer","producer"],"scripts":{"build":"tsc","test":"jest","test:watch":"jest --watch","prepublishOnly":"npm run build"},"peerDependencies":{"@nestjs/common":"^11.0.0","@nestjs/config":"^4.0.0","@nestjs/core":"^11.0.0","amqplib":"^0.10.0","reflect-metadata":"^0.2.0","rxjs":"^7.8.0"},"devDependencies":{"@types/amqplib":"^0.10.5","typescript":"^5.0.0","jest":"^29.0.0","@types/jest":"^29.0.0"},"repository":{"type":"git","url":"git+https://github.com/bvhoach2393/nest-rabbitmq.git"},"publishConfig":{"access":"public"},"_id":"@bvhoach2393/nest-rabbitmq@1.0.4","gitHead":"065cecfbb474f3784a447f0bb5a85bf938463497","bugs":{"url":"https://github.com/bvhoach2393/nest-rabbitmq/issues"},"homepage":"https://github.com/bvhoach2393/nest-rabbitmq#readme","_nodeVersion":"24.5.0","_npmVersion":"11.5.1","dist":{"integrity":"sha512-0i4x9re8U3MvHXoqOtOScSItpQ8RUd8q/HL1pEyiUb2gGU6c5153XJ/dLTSMcEWRT/9OHo9RnjBK0EFG/ciRnw==","shasum":"2c3df0560babc35baa3916508e263b10bc017e58","tarball":"https://registry.npmjs.org/@bvhoach2393/nest-rabbitmq/-/nest-rabbitmq-1.0.4.tgz","fileCount":4,"unpackedSize":13922,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIEENoPREMLZ/icG4o3S4ll0UVfNm3EyeUSxia6Vb1OQhAiEAg2U02hvalsY3oqCH1kC8Cb8/OgD0nLVwf9dKj7NEN0Q="}]},"_npmUser":{"name":"bvhoach2393","email":"bvhoach2393@gmail.com"},"directories":{},"maintainers":[{"name":"bvhoach2393","email":"bvhoach2393@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/nest-rabbitmq_1.0.4_1754626569344_0.9337916109881257"},"_hasShrinkwrap":false}},"time":{"created":"2025-07-17T12:37:08.646Z","modified":"2025-08-08T04:16:09.699Z","1.0.3":"2025-07-17T12:37:08.892Z","1.0.4":"2025-08-08T04:16:09.520Z"},"bugs":{"url":"https://github.com/bvhoach2393/nest-rabbitmq/issues"},"author":{"name":"bvhoach2393"},"license":"MIT","homepage":"https://github.com/bvhoach2393/nest-rabbitmq#readme","keywords":["nestjs","rabbitmq","message-queue","amqp","consumer","producer"],"repository":{"type":"git","url":"git+https://github.com/bvhoach2393/nest-rabbitmq.git"},"description":"NestJS RabbitMQ library for handling message queues with consumer and producer services","maintainers":[{"name":"bvhoach2393","email":"bvhoach2393@gmail.com"}],"readme":"# @bvhoach2393/nest-rabbitmq\n\nA comprehensive NestJS library for RabbitMQ integration that provides easy-to-use producer and consumer services with automatic connection management, message acknowledgment, and error handling.\n\n## Features\n\n- 🚀 **Easy Integration**: Simple setup with NestJS modules\n- 🔄 **Auto-Reconnection**: Automatic connection recovery and error handling\n- 📤 **Producer Service**: Send messages to exchanges or queues\n- 📥 **Consumer Service**: Consume messages with custom handlers\n- ⚙️ **Environment Configuration**: Configuration through environment variables\n- 🔒 **Type Safety**: Full TypeScript support with comprehensive interfaces\n- 📊 **Health Monitoring**: Connection health check methods\n- 🎯 **Message Patterns**: Support for request-reply messaging patterns\n- 🧪 **Well Tested**: Comprehensive unit tests included\n\n## Installation\n\n```bash\nnpm install @bvhoach2393/nest-rabbitmq\n```\n\n### Peer Dependencies\n\nMake sure you have the following peer dependencies installed:\n\n```bash\nnpm install @nestjs/common @nestjs/config @nestjs/core amqplib reflect-metadata rxjs\nnpm install -D @types/amqplib\n```\n\n## Configuration\n\n### Environment Variables\n\nSet up the following environment variables in your application:\n\n```env\n# RabbitMQ Connection\nRABBITMQ_HOST=localhost\nRABBITMQ_PORT=5672\nRABBITMQ_USERNAME=guest\nRABBITMQ_PASSWORD=guest\n\n# Exchanges, Routing Keys, and Queues (comma-separated, must have equal length)\nRABBITMQ_EXCHANGES=user.exchange,order.exchange,notification.exchange\nRABBITMQ_ROUTING_KEY=user.created,order.placed,notification.sent\nRABBITMQ_QUEUES=user.queue,order.queue,notification.queue\n```\n\n**Important**: The number of exchanges, routing keys, and queues must be equal. Each exchange will be bound to its corresponding queue using the corresponding routing key.\n\n## Usage\n\n### 1. Import the Module\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { NestRabbitmqModule } from '@bvhoach2393/nest-rabbitmq';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      isGlobal: true,\n    }),\n    NestRabbitmqModule.forRoot(), // For global usage\n  ],\n})\nexport class AppModule {}\n```\n\n### 2. Producer Usage\n\n```typescript\nimport { Injectable } from '@nestjs/common';\nimport { NestRabbitmqService } from '@bvhoach2393/nest-rabbitmq';\n\n@Injectable()\nexport class UserService {\n  constructor(private readonly rabbitmqService: NestRabbitmqService) {}\n\n  async createUser(userData: any) {\n    // Create user logic...\n    \n    // Publish message to exchange\n    await this.rabbitmqService.publish(\n      { userId: 123, action: 'created', data: userData },\n      {\n        exchange: 'user.exchange',\n        routingKey: 'user.created',\n        persistent: true,\n        timestamp: Date.now(),\n      }\n    );\n\n    // Or send directly to queue\n    await this.rabbitmqService.sendToQueue(\n      'user.queue',\n      { userId: 123, action: 'created' },\n      {\n        persistent: true,\n        correlationId: 'unique-id-123',\n      }\n    );\n  }\n}\n```\n\n### 3. Consumer Usage\n\n```typescript\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { NestRabbitmqService, RabbitMQMessage } from '@bvhoach2393/nest-rabbitmq';\n\n@Injectable()\nexport class UserConsumerService implements OnModuleInit {\n  constructor(private readonly rabbitmqService: NestRabbitmqService) {}\n\n  async onModuleInit() {\n    // Start consuming messages\n    await this.rabbitmqService.consume(\n      'user.queue',\n      this.handleUserMessage.bind(this),\n      {\n        noAck: false, // Manual acknowledgment\n      }\n    );\n  }\n\n  private async handleUserMessage(message: RabbitMQMessage): Promise<any> {\n    try {\n      const data = JSON.parse(message.content.toString());\n      console.log('Received user message:', data);\n\n      // Process the message\n      await this.processUser(data);\n\n      // Return response if replyTo is specified\n      if (message.properties.replyTo) {\n        return { status: 'success', userId: data.userId };\n      }\n    } catch (error) {\n      console.error('Error processing user message:', error);\n      throw error; // Will reject the message\n    }\n  }\n\n  private async processUser(data: any) {\n    // Your business logic here\n  }\n}\n```\n\n### 4. Request-Reply Pattern\n\n```typescript\n@Injectable()\nexport class OrderService {\n  constructor(private readonly rabbitmqService: NestRabbitmqService) {}\n\n  // Producer side - send message with replyTo\n  async validateOrder(orderData: any) {\n    await this.rabbitmqService.sendToQueue(\n      'validation.queue',\n      orderData,\n      {\n        replyTo: 'validation.reply.queue',\n        correlationId: `order-${Date.now()}`,\n      }\n    );\n  }\n\n  // Consumer side - handle and reply\n  async onModuleInit() {\n    await this.rabbitmqService.consume(\n      'validation.queue',\n      async (message: RabbitMQMessage) => {\n        const orderData = JSON.parse(message.content.toString());\n        const isValid = await this.validateOrderData(orderData);\n        \n        // Return response (will be sent to replyTo queue)\n        return { valid: isValid, orderId: orderData.id };\n      }\n    );\n  }\n}\n```\n\n### 5. Dynamic Exchange and Queue Management\n\n```typescript\n@Injectable()\nexport class DynamicQueueService {\n  constructor(private readonly rabbitmqService: NestRabbitmqService) {}\n\n  async createTemporaryQueue(name: string) {\n    // Create exchange\n    await this.rabbitmqService.createExchange('temp.exchange', 'direct');\n    \n    // Create queue\n    await this.rabbitmqService.createQueue(name, {\n      durable: false,\n      autoDelete: true,\n    });\n    \n    // Bind queue to exchange\n    await this.rabbitmqService.bindQueue(name, 'temp.exchange', 'temp.key');\n  }\n\n  async cleanupTemporaryQueue(name: string) {\n    // Unbind and delete\n    await this.rabbitmqService.unbindQueue(name, 'temp.exchange', 'temp.key');\n    await this.rabbitmqService.deleteQueue(name);\n    await this.rabbitmqService.deleteExchange('temp.exchange');\n  }\n}\n```\n\n### 6. Health Check\n\n```typescript\n@Injectable()\nexport class HealthService {\n  constructor(private readonly rabbitmqService: NestRabbitmqService) {}\n\n  checkRabbitMQHealth(): boolean {\n    return this.rabbitmqService.isConnectionHealthy();\n  }\n\n  getRabbitMQConfig() {\n    return this.rabbitmqService.getConfig();\n  }\n}\n```\n\n## API Reference\n\n### NestRabbitmqService\n\n#### Publishing Methods\n\n- `publish(message: any, options: PublishOptions): Promise<boolean>`\n- `sendToQueue(queue: string, message: any, options?: MessageOptions): Promise<boolean>`\n\n#### Consuming Methods\n\n- `consume(queue: string, handler: MessageHandler, options?: ConsumeOptions): Promise<void>`\n\n#### Management Methods\n\n- `createExchange(name: string, type?: string, options?: ExchangeOptions): Promise<void>`\n- `createQueue(name: string, options?: QueueOptions): Promise<void>`\n- `deleteExchange(name: string): Promise<void>`\n- `deleteQueue(name: string): Promise<void>`\n- `bindQueue(queue: string, exchange: string, routingKey: string): Promise<void>`\n- `unbindQueue(queue: string, exchange: string, routingKey: string): Promise<void>`\n\n#### Utility Methods\n\n- `isConnectionHealthy(): boolean`\n- `getConfig(): RabbitMQConfig`\n\n### Interfaces\n\n```typescript\ninterface PublishOptions extends MessageOptions {\n  exchange: string;\n  routingKey: string;\n  mandatory?: boolean;\n  immediate?: boolean;\n}\n\ninterface MessageOptions {\n  persistent?: boolean;\n  priority?: number;\n  expiration?: string;\n  timestamp?: number;\n  correlationId?: string;\n  replyTo?: string;\n  messageId?: string;\n  headers?: Record<string, any>;\n}\n\ninterface RabbitMQMessage {\n  content: Buffer;\n  fields: any;\n  properties: any;\n}\n```\n\n## Running Tests\n\n```bash\n# Unit tests\nnpm run test\n\n# Test coverage\nnpm run test:cov\n\n# Watch mode\nnpm run test:watch\n```\n\n## Error Handling\n\nThe library provides comprehensive error handling:\n\n- **Connection Errors**: Automatic logging and error throwing for connection issues\n- **Missing Configuration**: Clear error messages for missing environment variables\n- **Array Length Mismatch**: Validation for exchanges, routing keys, and queues arrays\n- **Message Processing Errors**: Proper message rejection and error logging\n\n## Best Practices\n\n1. **Environment Validation**: Always validate your environment variables before deploying\n2. **Message Acknowledgment**: Use manual acknowledgment (`noAck: false`) for important messages\n3. **Error Handling**: Implement proper try-catch blocks in message handlers\n4. **Connection Health**: Monitor connection health in production environments\n5. **Resource Cleanup**: Clean up unused exchanges and queues to avoid resource leaks\n\n## Publishing to NPM\n\n```bash\n# Build the library\nnpm run build\n\n# Publish to NPM registry\nnpm publish\n```\n\n## Contributing\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add some amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n\n## Support\n\nFor support and questions:\n- Create an issue on the GitHub repository\n- Check the documentation and examples above\n- Review the TypeScript interfaces for detailed method signatures\n\n## Changelog\n\nSee [CHANGELOG.md](./CHANGELOG.md) for detailed changes and version history.\n","readmeFilename":"README.md"}