@appinventiv/rabbit-mq 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,832 @@
1
+ # @developer-at/rabbit-mq
2
+
3
+ A comprehensive RabbitMQ client package for Node.js applications. Provides easy-to-use producer and consumer services with connection management, queue/exchange handling, and automatic reconnection.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @developer-at/rabbit-mq
9
+ ```
10
+
11
+ ## Features
12
+
13
+ - Producer service for publishing messages
14
+ - Consumer service for consuming messages
15
+ - Automatic connection management
16
+ - Queue and exchange creation
17
+ - Message acknowledgment handling
18
+ - Prefetch count configuration
19
+ - TypeScript support
20
+
21
+ ## Prerequisites
22
+
23
+ - RabbitMQ server running and accessible
24
+ - Connection URL (e.g., `amqp://localhost:5672`)
25
+
26
+ ## Usage
27
+
28
+ ### Basic Setup
29
+
30
+ First, configure the RabbitMQ connection:
31
+
32
+ ```typescript
33
+ import { RabbitMQManager, producer, consumer } from '@developer-at/rabbit-mq';
34
+
35
+ // Configure RabbitMQ connection
36
+ const manager = new RabbitMQManager();
37
+ manager.setConfig({
38
+ url: 'amqp://localhost:5672',
39
+ connectionOptions: {
40
+ // Optional connection options
41
+ }
42
+ });
43
+
44
+ // Connect to RabbitMQ
45
+ await manager.connect();
46
+ ```
47
+
48
+ ### Queue and Exchange Management
49
+
50
+ #### Creating Queues
51
+
52
+ Use the `createQueue` method from `RabbitMQManager` to create queues before using them:
53
+
54
+ ```typescript
55
+ import { RabbitMQManager } from '@developer-at/rabbit-mq';
56
+
57
+ const manager = new RabbitMQManager();
58
+ manager.setConfig({ url: 'amqp://localhost:5672' });
59
+ await manager.connect();
60
+
61
+ // Create a durable queue (survives broker restart)
62
+ await manager.createQueue({
63
+ name: 'user-events',
64
+ durable: true, // Queue persists after broker restart
65
+ exclusive: false, // Queue can be accessed by multiple connections
66
+ autoDelete: false // Queue is not deleted when unused
67
+ });
68
+
69
+ // Create a temporary queue (deleted when connection closes)
70
+ await manager.createQueue({
71
+ name: 'temp-queue',
72
+ durable: false,
73
+ exclusive: true, // Queue is exclusive to this connection
74
+ autoDelete: true // Queue is deleted when unused
75
+ });
76
+ ```
77
+
78
+ #### Creating Exchanges
79
+
80
+ Use the `createExchange` method to create exchanges for message routing:
81
+
82
+ ```typescript
83
+ import { RabbitMQManager } from '@developer-at/rabbit-mq';
84
+
85
+ const manager = new RabbitMQManager();
86
+ manager.setConfig({ url: 'amqp://localhost:5672' });
87
+ await manager.connect();
88
+
89
+ // Create a direct exchange (routes messages based on exact routing key match)
90
+ await manager.createExchange({
91
+ name: 'user-exchange',
92
+ type: 'direct', // Options: 'direct', 'topic', 'fanout', 'headers'
93
+ durable: true, // Exchange persists after broker restart
94
+ autoDelete: false // Exchange is not deleted when unused
95
+ });
96
+
97
+ // Create a topic exchange (routes messages based on pattern matching)
98
+ await manager.createExchange({
99
+ name: 'notifications',
100
+ type: 'topic',
101
+ durable: true
102
+ });
103
+
104
+ // Create a fanout exchange (broadcasts to all bound queues)
105
+ await manager.createExchange({
106
+ name: 'broadcast',
107
+ type: 'fanout',
108
+ durable: true
109
+ });
110
+ ```
111
+
112
+ #### Binding Queues to Exchanges
113
+
114
+ Use `bindQueue` to connect queues to exchanges with routing keys. The routing key determines which messages from the exchange are delivered to the queue:
115
+
116
+ ```typescript
117
+ import { RabbitMQManager } from '@developer-at/rabbit-mq';
118
+
119
+ const manager = new RabbitMQManager();
120
+ manager.setConfig({ url: 'amqp://localhost:5672' });
121
+ await manager.connect();
122
+
123
+ // Create exchange and queue first
124
+ await manager.createExchange({
125
+ name: 'user-exchange',
126
+ type: 'direct',
127
+ durable: true
128
+ });
129
+
130
+ await manager.createQueue({
131
+ name: 'user-created-queue',
132
+ durable: true
133
+ });
134
+
135
+ // Bind queue to exchange with routing key
136
+ // Messages published to 'user-exchange' with routing key 'user.created'
137
+ // will be routed to 'user-created-queue'
138
+ await manager.bindQueue('user-created-queue', 'user-exchange', 'user.created');
139
+
140
+ // You can bind the same queue to multiple routing keys
141
+ await manager.bindQueue('user-created-queue', 'user-exchange', 'user.updated');
142
+
143
+ // For fanout exchanges, routing key is ignored (all messages go to all bound queues)
144
+ await manager.createExchange({ name: 'broadcast', type: 'fanout', durable: true });
145
+ await manager.bindQueue('queue1', 'broadcast', ''); // routing key ignored for fanout
146
+ await manager.bindQueue('queue2', 'broadcast', ''); // routing key ignored for fanout
147
+ ```
148
+
149
+ **How Routing Works:**
150
+
151
+ - **Direct Exchange**: Routes messages where routing key exactly matches the binding key
152
+
153
+ - Example: Binding key `'user.created'` receives messages with routing key `'user.created'` only
154
+ - **Topic Exchange**: Routes messages using pattern matching (wildcards: `*` for single word, `#` for multiple words)
155
+
156
+ - Example: Binding key `'user.*'` receives `'user.created'`, `'user.updated'`, etc.
157
+ - Example: Binding key `'user.#'` receives `'user.created'`, `'user.profile.updated'`, etc.
158
+ - **Fanout Exchange**: Routes all messages to all bound queues (routing key is ignored)
159
+ - **Headers Exchange**: Routes based on message headers (not routing key)
160
+
161
+ ### Producer Usage
162
+
163
+ #### Simple Queue Producer (Without Exchange)
164
+
165
+ When you don't specify an exchange, messages are sent directly to the queue:
166
+
167
+ ```typescript
168
+ import { RabbitMQManager, producer } from '@developer-at/rabbit-mq';
169
+
170
+ // Setup connection
171
+ const manager = new RabbitMQManager();
172
+ manager.setConfig({ url: 'amqp://localhost:5672' });
173
+ await manager.connect();
174
+
175
+ // Create queue first (optional, but recommended)
176
+ await manager.createQueue({
177
+ name: 'user-events',
178
+ durable: true
179
+ });
180
+
181
+ // Publish message directly to queue (no exchange, no routing key)
182
+ await producer.produce('user-events', {
183
+ userId: '123',
184
+ action: 'user.created',
185
+ data: { name: 'John Doe', email: 'john@example.com' }
186
+ });
187
+ ```
188
+
189
+ #### Producer with Exchange and Routing Key
190
+
191
+ When using an exchange, you must specify both the exchange name and routing key. The routing key determines which bound queues receive the message:
192
+
193
+ ```typescript
194
+ import { RabbitMQManager, producer } from '@developer-at/rabbit-mq';
195
+
196
+ // Setup connection
197
+ const manager = new RabbitMQManager();
198
+ manager.setConfig({ url: 'amqp://localhost:5672' });
199
+ await manager.connect();
200
+
201
+ // Create exchange
202
+ await manager.createExchange({
203
+ name: 'user-exchange',
204
+ type: 'direct',
205
+ durable: true
206
+ });
207
+
208
+ // Create queues
209
+ await manager.createQueue({ name: 'user-created-queue', durable: true });
210
+ await manager.createQueue({ name: 'user-updated-queue', durable: true });
211
+
212
+ // Bind queues to exchange with different routing keys
213
+ await manager.bindQueue('user-created-queue', 'user-exchange', 'user.created');
214
+ await manager.bindQueue('user-updated-queue', 'user-exchange', 'user.updated');
215
+
216
+ // Publish message to exchange with routing key 'user.created'
217
+ // This message will be routed to 'user-created-queue' only
218
+ await producer.produce(
219
+ 'user-created-queue', // Queue name (used for binding reference)
220
+ { userId: '123', action: 'created', name: 'John Doe' },
221
+ 'user-exchange', // Exchange name
222
+ 'user.created' // Routing key - determines which queue receives the message
223
+ );
224
+
225
+ // Publish message with routing key 'user.updated'
226
+ // This message will be routed to 'user-updated-queue' only
227
+ await producer.produce(
228
+ 'user-updated-queue',
229
+ { userId: '123', action: 'updated', email: 'newemail@example.com' },
230
+ 'user-exchange',
231
+ 'user.updated'
232
+ );
233
+ ```
234
+
235
+ #### Topic Exchange Example with Pattern Matching
236
+
237
+ ```typescript
238
+ import { RabbitMQManager, producer } from '@developer-at/rabbit-mq';
239
+
240
+ const manager = new RabbitMQManager();
241
+ manager.setConfig({ url: 'amqp://localhost:5672' });
242
+ await manager.connect();
243
+
244
+ // Create topic exchange
245
+ await manager.createExchange({
246
+ name: 'notifications',
247
+ type: 'topic',
248
+ durable: true
249
+ });
250
+
251
+ // Create queues
252
+ await manager.createQueue({ name: 'email-queue', durable: true });
253
+ await manager.createQueue({ name: 'sms-queue', durable: true });
254
+ await manager.createQueue({ name: 'all-notifications-queue', durable: true });
255
+
256
+ // Bind with pattern matching
257
+ await manager.bindQueue('email-queue', 'notifications', 'notification.email.*');
258
+ await manager.bindQueue('sms-queue', 'notifications', 'notification.sms.*');
259
+ await manager.bindQueue('all-notifications-queue', 'notifications', 'notification.#');
260
+
261
+ // Publish to 'notification.email.user' - goes to email-queue and all-notifications-queue
262
+ await producer.produce(
263
+ 'email-queue',
264
+ { type: 'email', to: 'user@example.com', subject: 'Welcome' },
265
+ 'notifications',
266
+ 'notification.email.user'
267
+ );
268
+
269
+ // Publish to 'notification.sms.user' - goes to sms-queue and all-notifications-queue
270
+ await producer.produce(
271
+ 'sms-queue',
272
+ { type: 'sms', to: '+1234567890', message: 'Hello' },
273
+ 'notifications',
274
+ 'notification.sms.user'
275
+ );
276
+ ```
277
+
278
+ #### Fanout Exchange Example (Broadcast)
279
+
280
+ ```typescript
281
+ import { RabbitMQManager, producer } from '@developer-at/rabbit-mq';
282
+
283
+ const manager = new RabbitMQManager();
284
+ manager.setConfig({ url: 'amqp://localhost:5672' });
285
+ await manager.connect();
286
+
287
+ // Create fanout exchange
288
+ await manager.createExchange({
289
+ name: 'broadcast',
290
+ type: 'fanout',
291
+ durable: true
292
+ });
293
+
294
+ // Create multiple queues
295
+ await manager.createQueue({ name: 'queue1', durable: true });
296
+ await manager.createQueue({ name: 'queue2', durable: true });
297
+ await manager.createQueue({ name: 'queue3', durable: true });
298
+
299
+ // Bind all queues to fanout exchange (routing key is ignored)
300
+ await manager.bindQueue('queue1', 'broadcast', '');
301
+ await manager.bindQueue('queue2', 'broadcast', '');
302
+ await manager.bindQueue('queue3', 'broadcast', '');
303
+
304
+ // Publish message - ALL queues receive it (routing key is ignored for fanout)
305
+ await producer.produce(
306
+ 'queue1', // Any queue name works, all bound queues receive the message
307
+ { message: 'Broadcast to all queues' },
308
+ 'broadcast',
309
+ '' // Routing key is ignored for fanout exchanges
310
+ );
311
+ ```
312
+
313
+ ### Consumer Usage
314
+
315
+ #### Basic Consumer (Without Exchange)
316
+
317
+ When consuming from a queue without an exchange, messages are consumed directly from the queue:
318
+
319
+ ```typescript
320
+ import { RabbitMQManager, consumer } from '@developer-at/rabbit-mq';
321
+
322
+ // Setup connection
323
+ const manager = new RabbitMQManager();
324
+ manager.setConfig({ url: 'amqp://localhost:5672' });
325
+ await manager.connect();
326
+
327
+ // Create queue first (optional, but recommended)
328
+ await manager.createQueue({
329
+ name: 'user-events',
330
+ durable: true
331
+ });
332
+
333
+ // Start consuming messages directly from queue
334
+ // No exchange or routing key needed
335
+ await consumer.consume({
336
+ queue: 'user-events',
337
+ onMessage: async (message) => {
338
+ console.log('Received message:', message);
339
+
340
+ // Process the message
341
+ await processMessage(message);
342
+
343
+ // Message is automatically acknowledged on success
344
+ // Automatically nacked on error (not requeued)
345
+ }
346
+ });
347
+ ```
348
+
349
+ #### Consumer with Exchange and Routing Key
350
+
351
+ When consuming from an exchange-based setup, you need to specify the exchange and routing key that the queue is bound to:
352
+
353
+ ```typescript
354
+ import { RabbitMQManager, consumer } from '@developer-at/rabbit-mq';
355
+
356
+ // Setup connection
357
+ const manager = new RabbitMQManager();
358
+ manager.setConfig({ url: 'amqp://localhost:5672' });
359
+ await manager.connect();
360
+
361
+ // Create exchange
362
+ await manager.createExchange({
363
+ name: 'user-exchange',
364
+ type: 'direct',
365
+ durable: true
366
+ });
367
+
368
+ // Create queue
369
+ await manager.createQueue({
370
+ name: 'user-created-queue',
371
+ durable: true
372
+ });
373
+
374
+ // Bind queue to exchange with routing key
375
+ await manager.bindQueue('user-created-queue', 'user-exchange', 'user.created');
376
+
377
+ // Consume from queue that's bound to exchange
378
+ // You must specify the exchange and routing key that the queue is bound to
379
+ await consumer.consume({
380
+ queue: 'user-created-queue',
381
+ exchange: 'user-exchange', // Exchange name the queue is bound to
382
+ routingKey: 'user.created', // Routing key used in the binding
383
+ prefetchCount: 10, // Process up to 10 messages at a time
384
+ durable: true,
385
+ onMessage: async (message) => {
386
+ console.log('Received user created event:', message);
387
+ await handleUserCreated(message);
388
+ }
389
+ });
390
+ ```
391
+
392
+ #### Multiple Consumers with Different Routing Keys
393
+
394
+ ```typescript
395
+ import { RabbitMQManager, consumer } from '@developer-at/rabbit-mq';
396
+
397
+ const manager = new RabbitMQManager();
398
+ manager.setConfig({ url: 'amqp://localhost:5672' });
399
+ await manager.connect();
400
+
401
+ // Setup exchange
402
+ await manager.createExchange({
403
+ name: 'user-exchange',
404
+ type: 'direct',
405
+ durable: true
406
+ });
407
+
408
+ // Create queues for different events
409
+ await manager.createQueue({ name: 'user-created-queue', durable: true });
410
+ await manager.createQueue({ name: 'user-updated-queue', durable: true });
411
+ await manager.createQueue({ name: 'user-deleted-queue', durable: true });
412
+
413
+ // Bind queues with different routing keys
414
+ await manager.bindQueue('user-created-queue', 'user-exchange', 'user.created');
415
+ await manager.bindQueue('user-updated-queue', 'user-exchange', 'user.updated');
416
+ await manager.bindQueue('user-deleted-queue', 'user-exchange', 'user.deleted');
417
+
418
+ // Consumer for user.created events
419
+ await consumer.consume({
420
+ queue: 'user-created-queue',
421
+ exchange: 'user-exchange',
422
+ routingKey: 'user.created',
423
+ onMessage: async (message) => {
424
+ console.log('User created:', message);
425
+ }
426
+ });
427
+
428
+ // Consumer for user.updated events
429
+ await consumer.consume({
430
+ queue: 'user-updated-queue',
431
+ exchange: 'user-exchange',
432
+ routingKey: 'user.updated',
433
+ onMessage: async (message) => {
434
+ console.log('User updated:', message);
435
+ }
436
+ });
437
+
438
+ // Consumer for user.deleted events
439
+ await consumer.consume({
440
+ queue: 'user-deleted-queue',
441
+ exchange: 'user-exchange',
442
+ routingKey: 'user.deleted',
443
+ onMessage: async (message) => {
444
+ console.log('User deleted:', message);
445
+ }
446
+ });
447
+ ```
448
+
449
+ #### Topic Exchange Consumer with Pattern Matching
450
+
451
+ ```typescript
452
+ import { RabbitMQManager, consumer } from '@developer-at/rabbit-mq';
453
+
454
+ const manager = new RabbitMQManager();
455
+ manager.setConfig({ url: 'amqp://localhost:5672' });
456
+ await manager.connect();
457
+
458
+ // Create topic exchange
459
+ await manager.createExchange({
460
+ name: 'notifications',
461
+ type: 'topic',
462
+ durable: true
463
+ });
464
+
465
+ // Create queue for email notifications
466
+ await manager.createQueue({ name: 'email-notifications', durable: true });
467
+
468
+ // Bind with pattern - receives all email.* notifications
469
+ await manager.bindQueue('email-notifications', 'notifications', 'notification.email.*');
470
+
471
+ // Consumer receives messages matching the pattern
472
+ await consumer.consume({
473
+ queue: 'email-notifications',
474
+ exchange: 'notifications',
475
+ routingKey: 'notification.email.*', // Pattern used in binding
476
+ onMessage: async (message) => {
477
+ console.log('Email notification:', message);
478
+ // Receives: notification.email.user, notification.email.admin, etc.
479
+ }
480
+ });
481
+ ```
482
+
483
+ ### Complete Examples
484
+
485
+ #### Example 1: Simple Queue (No Exchange)
486
+
487
+ ```typescript
488
+ import { RabbitMQManager, producer, consumer } from '@developer-at/rabbit-mq';
489
+
490
+ async function setupSimpleQueue() {
491
+ // Initialize connection
492
+ const manager = new RabbitMQManager();
493
+ manager.setConfig({
494
+ url: process.env.RABBITMQ_URL || 'amqp://localhost:5672'
495
+ });
496
+
497
+ await manager.connect();
498
+
499
+ // Create queue
500
+ await manager.createQueue({
501
+ name: 'user-events',
502
+ durable: true
503
+ });
504
+
505
+ // Producer - send directly to queue (no exchange, no routing key)
506
+ await producer.produce('user-events', {
507
+ type: 'user.created',
508
+ userId: '123',
509
+ name: 'John Doe'
510
+ });
511
+
512
+ // Consumer - consume directly from queue (no exchange, no routing key)
513
+ await consumer.consume({
514
+ queue: 'user-events',
515
+ prefetchCount: 5,
516
+ onMessage: async (message) => {
517
+ try {
518
+ console.log('Processing:', message);
519
+ await processUserEvent(message);
520
+ } catch (error) {
521
+ console.error('Error processing message:', error);
522
+ }
523
+ }
524
+ });
525
+ }
526
+ ```
527
+
528
+ #### Example 2: Exchange-Based with Routing Keys
529
+
530
+ ```typescript
531
+ import { RabbitMQManager, producer, consumer } from '@developer-at/rabbit-mq';
532
+
533
+ async function setupExchangeBased() {
534
+ const manager = new RabbitMQManager();
535
+ manager.setConfig({
536
+ url: process.env.RABBITMQ_URL || 'amqp://localhost:5672'
537
+ });
538
+
539
+ await manager.connect();
540
+
541
+ // Create exchange
542
+ await manager.createExchange({
543
+ name: 'user-exchange',
544
+ type: 'direct',
545
+ durable: true
546
+ });
547
+
548
+ // Create queues
549
+ await manager.createQueue({ name: 'user-created-queue', durable: true });
550
+ await manager.createQueue({ name: 'user-updated-queue', durable: true });
551
+
552
+ // Bind queues to exchange with routing keys
553
+ await manager.bindQueue('user-created-queue', 'user-exchange', 'user.created');
554
+ await manager.bindQueue('user-updated-queue', 'user-exchange', 'user.updated');
555
+
556
+ // Producer - publish to exchange with routing key
557
+ await producer.produce(
558
+ 'user-created-queue',
559
+ { userId: '123', action: 'created', name: 'John Doe' },
560
+ 'user-exchange', // Exchange name
561
+ 'user.created' // Routing key - routes to user-created-queue
562
+ );
563
+
564
+ // Consumer - consume from queue bound to exchange
565
+ await consumer.consume({
566
+ queue: 'user-created-queue',
567
+ exchange: 'user-exchange', // Exchange name
568
+ routingKey: 'user.created', // Routing key used in binding
569
+ prefetchCount: 5,
570
+ onMessage: async (message) => {
571
+ try {
572
+ console.log('User created event:', message);
573
+ await handleUserCreated(message);
574
+ } catch (error) {
575
+ console.error('Error processing message:', error);
576
+ }
577
+ }
578
+ });
579
+ }
580
+
581
+ // Graceful shutdown
582
+ process.on('SIGTERM', async () => {
583
+ await producer.disconnectAll();
584
+ await consumer.disconnectConsumers();
585
+ process.exit(0);
586
+ });
587
+ ```
588
+
589
+ ## API Reference
590
+
591
+ ### RabbitMQManager
592
+
593
+ Base class for managing RabbitMQ connections.
594
+
595
+ #### `setConfig(config: IRabbitMQConfig)`
596
+
597
+ Sets the RabbitMQ connection configuration.
598
+
599
+ **Parameters:**
600
+
601
+ - `config.url` (string): RabbitMQ connection URL
602
+ - `config.connectionOptions` (any, optional): Additional connection options
603
+
604
+ #### `connect()`
605
+
606
+ Establishes connection to RabbitMQ.
607
+
608
+ #### `disconnect()`
609
+
610
+ Closes the RabbitMQ connection.
611
+
612
+ #### `createQueue(queueConfig: IQueueConfig)`
613
+
614
+ Creates a queue if it doesn't exist. This method should be called after connecting to RabbitMQ.
615
+
616
+ **Parameters:**
617
+
618
+ - `queueConfig.name` (string): Queue name
619
+ - `queueConfig.durable` (boolean, optional): Queue survives broker restart (default: true)
620
+ - `queueConfig.exclusive` (boolean, optional): Queue is exclusive to connection (default: false)
621
+ - `queueConfig.autoDelete` (boolean, optional): Queue is deleted when unused (default: false)
622
+ - `queueConfig.arguments` (any, optional): Additional queue arguments
623
+
624
+ **Example:**
625
+
626
+ ```typescript
627
+ await manager.createQueue({
628
+ name: 'my-queue',
629
+ durable: true,
630
+ exclusive: false,
631
+ autoDelete: false
632
+ });
633
+ ```
634
+
635
+ #### `createExchange(exchangeConfig: IExchangeConfig)`
636
+
637
+ Creates an exchange if it doesn't exist. This method should be called after connecting to RabbitMQ.
638
+
639
+ **Parameters:**
640
+
641
+ - `exchangeConfig.name` (string): Exchange name
642
+ - `exchangeConfig.type` ('direct' | 'topic' | 'fanout' | 'headers'): Exchange type
643
+ - `direct`: Routes messages where routing key exactly matches binding key
644
+ - `topic`: Routes messages using pattern matching (wildcards: `*`, `#`)
645
+ - `fanout`: Broadcasts all messages to all bound queues (routing key ignored)
646
+ - `headers`: Routes based on message headers
647
+ - `exchangeConfig.durable` (boolean, optional): Exchange survives broker restart (default: true)
648
+ - `exchangeConfig.autoDelete` (boolean, optional): Exchange is deleted when unused (default: false)
649
+ - `exchangeConfig.arguments` (any, optional): Additional exchange arguments
650
+
651
+ **Example:**
652
+
653
+ ```typescript
654
+ await manager.createExchange({
655
+ name: 'my-exchange',
656
+ type: 'direct',
657
+ durable: true
658
+ });
659
+ ```
660
+
661
+ #### `bindQueue(queueName: string, exchangeName: string, routingKey?: string)`
662
+
663
+ Binds a queue to an exchange with an optional routing key. The routing key determines which messages from the exchange are delivered to the queue.
664
+
665
+ **Parameters:**
666
+
667
+ - `queueName` (string): Name of the queue to bind
668
+ - `exchangeName` (string): Name of the exchange to bind to
669
+ - `routingKey` (string, optional): Routing key for message filtering (default: '')
670
+
671
+ **How Routing Works:**
672
+
673
+ - **Direct Exchange**: Routing key must exactly match the binding key
674
+ - **Topic Exchange**: Routing key can use wildcards (`*` for single word, `#` for multiple words)
675
+ - **Fanout Exchange**: Routing key is ignored, all messages go to all bound queues
676
+ - **Headers Exchange**: Routing key is ignored, routing is based on message headers
677
+
678
+ **Example:**
679
+
680
+ ```typescript
681
+ // Direct exchange - exact match
682
+ await manager.bindQueue('queue1', 'exchange1', 'user.created');
683
+
684
+ // Topic exchange - pattern matching
685
+ await manager.bindQueue('queue2', 'exchange2', 'user.*'); // Matches user.created, user.updated, etc.
686
+ await manager.bindQueue('queue3', 'exchange2', 'user.#'); // Matches user.created, user.profile.updated, etc.
687
+
688
+ // Fanout exchange - routing key ignored
689
+ await manager.bindQueue('queue4', 'exchange3', ''); // All messages received
690
+ ```
691
+
692
+ ### Producer Service
693
+
694
+ #### `produce(queue: string, message: any, exchange?: string, routingKey?: string)`
695
+
696
+ Publishes a message to a queue or exchange.
697
+
698
+ **Parameters:**
699
+
700
+ - `queue` (string): Queue name (used as reference, actual routing depends on exchange/routing key)
701
+ - `message` (any): Message payload (will be JSON stringified)
702
+ - `exchange` (string, optional): Exchange name. If provided, message is published to exchange with routing key
703
+ - `routingKey` (string, optional): Routing key for exchange. Required when using exchange
704
+
705
+ **Usage Patterns:**
706
+
707
+ 1. **Direct Queue (No Exchange):**
708
+
709
+ ```typescript
710
+ // Message sent directly to queue
711
+ await producer.produce('my-queue', { data: 'value' });
712
+ ```
713
+ 2. **With Exchange and Routing Key:**
714
+
715
+ ```typescript
716
+ // Message published to exchange, routed to queues based on routing key
717
+ await producer.produce('my-queue', { data: 'value' }, 'my-exchange', 'routing.key');
718
+ ```
719
+
720
+ **Important Notes:**
721
+
722
+ - When using an exchange, the routing key determines which bound queues receive the message
723
+ - The queue parameter is used as a reference but doesn't affect routing when using an exchange
724
+ - For fanout exchanges, routing key is ignored and all bound queues receive the message
725
+
726
+ #### `disconnectAll()`
727
+
728
+ Disconnects all active producers.
729
+
730
+ #### `getProducerCount(): number`
731
+
732
+ Returns the number of active producers.
733
+
734
+ #### `getProducerKeys(): string[]`
735
+
736
+ Returns all producer keys.
737
+
738
+ ### Consumer Service
739
+
740
+ #### `consume(options: IRabbitMQConsumerOptions)`
741
+
742
+ Starts consuming messages from a queue. If the queue is bound to an exchange, you must specify the exchange and routing key that was used in the binding.
743
+
744
+ **Parameters:**
745
+
746
+ - `options.queue` (string): Queue name to consume from
747
+ - `options.exchange` (string, optional): Exchange name the queue is bound to. Required if queue is bound to an exchange
748
+ - `options.routingKey` (string, optional): Routing key used in the queue binding. Required if queue is bound to an exchange
749
+ - `options.onMessage` (function): Async function to handle messages. Receives parsed message object
750
+ - `options.prefetchCount` (number, optional): Number of unacknowledged messages to process concurrently (default: 1)
751
+ - `options.durable` (boolean, optional): Queue durability (default: true)
752
+ - `options.exclusive` (boolean, optional): Queue exclusivity (default: false)
753
+ - `options.autoDelete` (boolean, optional): Auto-delete queue when unused (default: false)
754
+
755
+ **Usage Patterns:**
756
+
757
+ 1. **Direct Queue (No Exchange):**
758
+
759
+ ```typescript
760
+ await consumer.consume({
761
+ queue: 'my-queue',
762
+ onMessage: async (message) => {
763
+ // Process message
764
+ }
765
+ });
766
+ ```
767
+ 2. **Queue Bound to Exchange:**
768
+
769
+ ```typescript
770
+ await consumer.consume({
771
+ queue: 'my-queue',
772
+ exchange: 'my-exchange', // Must match the exchange used in binding
773
+ routingKey: 'routing.key', // Must match the routing key used in binding
774
+ onMessage: async (message) => {
775
+ // Process message
776
+ }
777
+ });
778
+ ```
779
+
780
+ **Important Notes:**
781
+
782
+ - If a queue is bound to an exchange, you MUST specify both `exchange` and `routingKey` in the consume options
783
+ - The `exchange` and `routingKey` must match the values used when binding the queue to the exchange
784
+ - For queues not bound to an exchange, omit `exchange` and `routingKey` parameters
785
+
786
+ #### `disconnectConsumers()`
787
+
788
+ Disconnects all active consumers.
789
+
790
+ #### `getConsumerCount(): number`
791
+
792
+ Returns the number of active consumers.
793
+
794
+ #### `getConsumerTags(): string[]`
795
+
796
+ Returns all consumer tags.
797
+
798
+ ## Message Handling
799
+
800
+ - Messages are automatically acknowledged on successful processing
801
+ - Messages are automatically nacked (not requeued) on error
802
+ - Use `prefetchCount` to control concurrency
803
+ - Messages are JSON stringified when publishing and parsed when consuming
804
+
805
+ ## Error Handling
806
+
807
+ The package includes automatic error handling:
808
+
809
+ - Connection errors are logged
810
+ - Failed messages are nacked (not requeued)
811
+ - Automatic reconnection on connection loss
812
+
813
+ ## TypeScript Support
814
+
815
+ Full TypeScript definitions are included. Import interfaces for type safety:
816
+
817
+ ```typescript
818
+ import {
819
+ IRabbitMQConfig,
820
+ IRabbitMQConsumerOptions,
821
+ IRabbitMQProducerOptions,
822
+ IRabbitMQMessage
823
+ } from '@developer-at/rabbit-mq';
824
+ ```
825
+
826
+ ## Dependencies
827
+
828
+ - `amqplib`: ^0.10.9
829
+
830
+ ## License
831
+
832
+ ISC