@appinventiv/rabbit-mq 1.0.0 → 1.0.4

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.
@@ -1,50 +1,46 @@
1
1
  import { IRabbitMQConsumer, IRabbitMQConsumerOptions } from '../interface';
2
- import { RabbitMQManager } from '../rabbitmq';
2
+ import { rabbitMQ, RabbitMQManager } from '../rabbitmq';
3
3
 
4
4
  /**
5
5
  * @description RabbitMQ consumer class for consuming messages from queues
6
- * Extends RabbitMQManager to provide message consumption functionality with automatic acknowledgment
6
+ * Uses a composed RabbitMQManager instance (default: package singleton `rabbitMQ`)
7
+ * Provides message consumption with automatic acknowledgment
7
8
  */
8
- export class RabbitMQConsumer extends RabbitMQManager implements IRabbitMQConsumer {
9
+ export class RabbitMQConsumer implements IRabbitMQConsumer {
10
+ private readonly rabbitMq: RabbitMQManager;
9
11
  private readonly queue: string;
10
12
  private readonly exchange?: string;
11
13
  private readonly routingKey?: string;
12
14
  private readonly onMessage: (message: any) => Promise<void>;
13
15
  private readonly prefetchCount: number;
14
- private readonly durable: boolean;
15
- private readonly exclusive: boolean;
16
- private readonly autoDelete: boolean;
17
16
  private consumerTag?: string;
18
17
 
19
18
  /**
20
19
  * @description Initialize RabbitMQ consumer with configuration
21
- * @param {IRabbitMQConsumerOptions} options - Consumer configuration options
20
+ * @param {IRabbitMQConsumerOptions} options - Consumer configuration options (queue, onMessage, optional `rabbitMq`)
22
21
  */
23
22
  constructor(options: IRabbitMQConsumerOptions) {
24
- super();
23
+ this.rabbitMq = options.rabbitMq ?? rabbitMQ;
25
24
  this.queue = options.queue;
26
25
  this.exchange = options.exchange;
27
26
  this.routingKey = options.routingKey || '';
28
27
  this.onMessage = options.onMessage;
29
28
  this.prefetchCount = options.prefetchCount || 1;
30
- this.durable = options.durable ?? true;
31
- this.exclusive = options.exclusive ?? false;
32
- this.autoDelete = options.autoDelete ?? false;
33
29
  }
34
30
 
35
31
  /**
36
- * @description Consume Message From Queue
37
- * @param onMessage - Function to be executed on Message
32
+ * @description Consume messages from the configured queue
33
+ * Invokes `onMessage` for each message; ack on success, nack without requeue on failure
38
34
  */
39
35
  async consumeEachMessage() {
40
36
  try {
41
- if (!this.isConnected()) {
42
- await this.reconnect();
37
+ if (!this.rabbitMq.isConnected()) {
38
+ await this.rabbitMq.reconnect();
43
39
  }
44
40
 
45
- const channel = this.getChannel();
41
+ const channel = this.rabbitMq.getChannel();
46
42
 
47
- // Set prefetch count
43
+ // Set prefetch count for fair dispatch
48
44
  await channel.prefetch(this.prefetchCount);
49
45
 
50
46
  // Setup queue and exchange if needed
@@ -88,11 +84,13 @@ export class RabbitMQConsumer extends RabbitMQManager implements IRabbitMQConsum
88
84
  }
89
85
 
90
86
  /**
91
- * @description Open Connection
87
+ * @description Open connection (via manager) and start consuming
92
88
  */
93
89
  async connect() {
94
90
  try {
95
- await super.connect();
91
+ if (!this.rabbitMq.isConnected()) {
92
+ await this.rabbitMq.connect();
93
+ }
96
94
  await this.consumeEachMessage();
97
95
  } catch (error: any) {
98
96
  console.error(`Error-- Failed to connect to RabbitMQ --msg :: `, error);
@@ -101,49 +99,71 @@ export class RabbitMQConsumer extends RabbitMQManager implements IRabbitMQConsum
101
99
  }
102
100
 
103
101
  /**
104
- * @description Close Connection
102
+ * @description Cancel consumer and optionally disconnect dedicated manager
103
+ * Does not close the default `rabbitMQ` singleton connection
105
104
  */
106
105
  async disconnect() {
107
106
  try {
108
- if (this.consumerTag && this.channel) {
109
- await this.channel.cancel(this.consumerTag);
110
- console.info(`RabbitMQ Consumer cancelled: ${this.consumerTag}`);
107
+ if (this.consumerTag && this.rabbitMq.isConnected()) {
108
+ try {
109
+ const channel = this.rabbitMq.getChannel();
110
+ await channel.cancel(this.consumerTag);
111
+ console.info(`RabbitMQ Consumer cancelled: ${this.consumerTag}`);
112
+ } catch (error: any) {
113
+ console.error('Error cancelling RabbitMQ consumer:', error);
114
+ }
115
+ }
116
+ this.consumerTag = undefined;
117
+
118
+ if (this.rabbitMq !== rabbitMQ) {
119
+ await this.rabbitMq.disconnect();
111
120
  }
112
- await super.disconnect();
113
121
  } catch (error: any) {
114
122
  console.error('Error disconnecting RabbitMQ Consumer:', error);
115
123
  }
116
124
  }
117
125
 
118
126
  /**
119
- * @description Register event handlers
127
+ * @description Register connection and channel event handlers
120
128
  */
121
129
  async registerEvents() {
122
- if (this.connection) {
123
- this.connection.on('error', (error: any) => {
130
+ const connection = this.rabbitMq.getConnection();
131
+
132
+ if (connection) {
133
+ connection.on('error', (error: any) => {
124
134
  console.error(`Error-- RabbitMQ Consumer Connection Error --msg :: `, error);
125
135
  });
126
136
 
127
- this.connection.on('close', () => {
137
+ connection.on('close', () => {
128
138
  console.warn('RabbitMQ Consumer Connection Closed');
129
139
  });
130
140
  }
131
141
 
132
- if (this.channel) {
133
- this.channel.on('error', (error: any) => {
142
+ if (this.rabbitMq.isConnected()) {
143
+ const channel = this.rabbitMq.getChannel();
144
+ channel.on('error', (error: any) => {
134
145
  console.error(`Error-- RabbitMQ Consumer Channel Error --msg :: `, error);
135
146
  });
136
147
 
137
- this.channel.on('close', () => {
148
+ channel.on('close', () => {
138
149
  console.warn('RabbitMQ Consumer Channel Closed');
139
150
  });
140
151
  }
141
152
  }
142
153
 
143
154
  /**
144
- * @description Get consumer tag
155
+ * @description Get consumer tag assigned by RabbitMQ
156
+ * @returns {string | undefined} Consumer tag when consuming is active
145
157
  */
146
158
  getConsumerTag(): string | undefined {
147
159
  return this.consumerTag;
148
160
  }
161
+
162
+ /**
163
+ * @description Get the RabbitMQ manager instance used by this consumer
164
+ * @returns {RabbitMQManager} Composed manager
165
+ */
166
+ getRabbitMq(): RabbitMQManager {
167
+ return this.rabbitMq;
168
+ }
149
169
  }
@@ -1,42 +1,46 @@
1
- import { IRabbitMQConsumerOptions, IRabbitMQConsumer, IRabbitMQMessage } from '../interface';
1
+ import { IRabbitMQConsumer, IRabbitMQConsumerOptions } from '../interface';
2
+ import { rabbitMQ, RabbitMQManager } from '../rabbitmq';
2
3
  import { RabbitMQConsumer } from './consumer.rabbitmq';
3
4
 
4
5
  /**
5
6
  * @description Consumer service for managing multiple RabbitMQ consumers
6
7
  * Provides centralized management for multiple queue consumers
7
8
  */
8
- class ConsumerService {
9
+ export class ConsumerService {
9
10
  private readonly consumers: IRabbitMQConsumer[] = [];
10
11
 
11
12
  /**
12
- * @description Start Consumer for Queue
13
- * @param {IRabbitMQConsumerOptions} payload
13
+ * @description Optional default RabbitMQ manager when not passed per consume() call
14
+ * @param {RabbitMQManager} defaultRabbitMq - Falls back to package singleton `rabbitMQ` when omitted
14
15
  */
15
- async consume({ queue, exchange, routingKey, onMessage, prefetchCount, durable, exclusive, autoDelete }: IRabbitMQConsumerOptions) {
16
+ constructor(private readonly defaultRabbitMq?: RabbitMQManager) {}
17
+
18
+ /**
19
+ * @description Start consumer for a queue (and optional exchange / routing key)
20
+ * Uses `options.rabbitMq`, then service default, then singleton `rabbitMQ`.
21
+ * @param {IRabbitMQConsumerOptions} options - Queue name, handler, prefetch, and optional `rabbitMq` instance
22
+ */
23
+ async consume(options: IRabbitMQConsumerOptions) {
16
24
  try {
25
+ const manager = options.rabbitMq ?? this.defaultRabbitMq ?? rabbitMQ;
17
26
  const consumer = new RabbitMQConsumer({
18
- queue,
19
- exchange,
20
- routingKey,
21
- onMessage,
22
- prefetchCount,
23
- durable,
24
- exclusive,
25
- autoDelete
27
+ ...options,
28
+ rabbitMq: manager
26
29
  });
27
30
 
28
31
  await consumer.connect();
29
32
  await consumer.registerEvents();
30
33
  this.consumers.push(consumer);
31
34
 
32
- console.info(`RabbitMQ Consumer started for queue: ${queue}`);
35
+ console.info(`RabbitMQ Consumer started for queue: ${options.queue}`);
33
36
  } catch (error: any) {
34
37
  console.error(`Error-- RabbitMQ Consumer --msg :: `, error);
35
38
  }
36
39
  }
37
40
 
38
41
  /**
39
- * @description Initiate RabbitMQ Consumer for Each Queue
42
+ * @description Initiate RabbitMQ consumer for each queue
43
+ * Add app-specific consumer registrations inside this method if needed
40
44
  */
41
45
  async initiateConsumer() {
42
46
  try {
@@ -47,7 +51,9 @@ class ConsumerService {
47
51
  }
48
52
 
49
53
  /**
50
- * @description Disconnect Consumers
54
+ * @description Disconnect all registered consumers
55
+ * Cancels consumer tags; does not close the default `rabbitMQ` singleton connection.
56
+ * Call `rabbitMQ.disconnect()` at application shutdown to close the shared connection.
51
57
  */
52
58
  async disconnectConsumers() {
53
59
  for (const consumer of this.consumers) {
@@ -62,18 +68,23 @@ class ConsumerService {
62
68
  }
63
69
 
64
70
  /**
65
- * @description Get consumer count
71
+ * @description Get the number of active consumers managed by this service
72
+ * @returns {number} Consumer count
66
73
  */
67
74
  getConsumerCount(): number {
68
75
  return this.consumers.length;
69
76
  }
70
77
 
71
78
  /**
72
- * @description Get all consumer tags
79
+ * @description Get all consumer tags from active consumers
80
+ * @returns {string[]} List of RabbitMQ consumer tags
73
81
  */
74
82
  getConsumerTags(): string[] {
75
- return this.consumers.map((consumer) => (consumer as RabbitMQConsumer).getConsumerTag()).filter((tag) => tag !== undefined) as string[];
83
+ return this.consumers
84
+ .map((c) => (c as RabbitMQConsumer).getConsumerTag())
85
+ .filter((tag): tag is string => tag !== undefined);
76
86
  }
77
87
  }
78
88
 
89
+ /** Pre-configured consumer service singleton */
79
90
  export const consumer = new ConsumerService();
package/src/index.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export * from './rabbitmq';
2
2
  export * from './producer/producer.service';
3
+ export * from './producer/producer.rabbitmq';
3
4
  export * from './consumer/consumer.service';
4
- export * from './interface';
5
+ export * from './consumer/consumer.rabbitmq';
6
+ export * from './interface';
package/src/interface.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { RabbitMQManager } from './rabbitmq';
2
+
1
3
  interface IRabbitMQConnection {
2
4
  connect: () => Promise<void>;
3
5
  disconnect: () => Promise<void>;
@@ -8,7 +10,8 @@ export interface IRabbitMQProducer extends IRabbitMQConnection {
8
10
  }
9
11
 
10
12
  export interface IRabbitMQConsumer extends IRabbitMQConnection {
11
- consumeEachMessage: (message: any) => Promise<void>;
13
+ consumeEachMessage: () => Promise<void>;
14
+ registerEvents: () => Promise<void>;
12
15
  }
13
16
 
14
17
  export interface IRabbitMQConsumerOptions {
@@ -20,7 +23,10 @@ export interface IRabbitMQConsumerOptions {
20
23
  durable?: boolean;
21
24
  exclusive?: boolean;
22
25
  autoDelete?: boolean;
26
+ /** Optional manager instance; defaults to package singleton `rabbitMQ` */
27
+ rabbitMq?: RabbitMQManager;
23
28
  }
29
+
24
30
  export interface IRabbitMQProducerOptions {
25
31
  queue: string;
26
32
  exchange?: string;
@@ -29,7 +35,10 @@ export interface IRabbitMQProducerOptions {
29
35
  exclusive?: boolean;
30
36
  autoDelete?: boolean;
31
37
  persistent?: boolean;
38
+ /** Optional manager instance; defaults to package singleton `rabbitMQ` */
39
+ rabbitMq?: RabbitMQManager;
32
40
  }
41
+
33
42
  export interface IRabbitMQConfig {
34
43
  url: string;
35
44
  connectionOptions?: any;
@@ -57,5 +66,4 @@ export interface IMessagePayload {
57
66
  }
58
67
 
59
68
  // RabbitMQ message - allows both generic and specific message types
60
- // Using intersection type to allow both index signature and specific properties
61
69
  export type IRabbitMQMessage = IMessagePayload & { [key: string]: unknown };
@@ -0,0 +1,11 @@
1
+ import { rabbitMQ, RabbitMQManager } from './rabbitmq';
2
+
3
+ /**
4
+ * @description Pool key prefix for grouping producers by RabbitMQ manager instance
5
+ */
6
+ export function getManagerPoolKey(manager: RabbitMQManager): string {
7
+ if (manager === rabbitMQ) {
8
+ return 'default';
9
+ }
10
+ return manager.getUrl() ?? 'custom';
11
+ }
@@ -1,22 +1,23 @@
1
1
  import { IRabbitMQProducer, IRabbitMQProducerOptions } from '../interface';
2
- import { RabbitMQManager } from '../rabbitmq';
2
+ import { rabbitMQ, RabbitMQManager } from '../rabbitmq';
3
3
 
4
4
  /**
5
5
  * @description RabbitMQ producer class for publishing messages to queues or exchanges
6
- * Extends RabbitMQManager to provide message publishing functionality
6
+ * Uses a composed RabbitMQManager instance (default: package singleton `rabbitMQ`)
7
7
  */
8
- export class RabbitMQProducer extends RabbitMQManager implements IRabbitMQProducer {
9
- private queue: string;
10
- private exchange?: string;
11
- private routingKey?: string;
12
- private persistent: boolean;
8
+ export class RabbitMQProducer implements IRabbitMQProducer {
9
+ private readonly rabbitMq: RabbitMQManager;
10
+ private readonly queue: string;
11
+ private readonly exchange?: string;
12
+ private readonly routingKey?: string;
13
+ private readonly persistent: boolean;
13
14
 
14
15
  /**
15
16
  * @description Initialize RabbitMQ producer with configuration
16
- * @param {IRabbitMQProducerOptions} options - Producer configuration options
17
+ * @param {IRabbitMQProducerOptions} options - Producer configuration options (queue, exchange, routing key, optional `rabbitMq`)
17
18
  */
18
19
  constructor(options: IRabbitMQProducerOptions) {
19
- super();
20
+ this.rabbitMq = options.rabbitMq ?? rabbitMQ;
20
21
  this.queue = options.queue;
21
22
  this.exchange = options.exchange;
22
23
  this.routingKey = options.routingKey || '';
@@ -24,20 +25,20 @@ export class RabbitMQProducer extends RabbitMQManager implements IRabbitMQProduc
24
25
  }
25
26
 
26
27
  /**
27
- * @description Publish Message to RabbitMQ Queue/Exchange
28
- * @param {any} message
28
+ * @description Publish message to RabbitMQ queue or exchange
29
+ * @param {any} message - Payload serialized as JSON
29
30
  */
30
31
  async produce(message: any) {
31
32
  try {
32
- if (!this.isConnected()) {
33
- await this.reconnect();
33
+ if (!this.rabbitMq.isConnected()) {
34
+ await this.rabbitMq.reconnect();
34
35
  }
35
36
 
36
- const channel = this.getChannel();
37
+ const channel = this.rabbitMq.getChannel();
37
38
  const messageBuffer = Buffer.from(JSON.stringify(message));
38
39
 
39
40
  if (this.exchange) {
40
- // Publish to exchange
41
+ // Publish to exchange with routing key
41
42
  channel.publish(this.exchange, this.routingKey || '', messageBuffer, {
42
43
  persistent: this.persistent,
43
44
  timestamp: Date.now()
@@ -58,29 +59,29 @@ export class RabbitMQProducer extends RabbitMQManager implements IRabbitMQProduc
58
59
  }
59
60
 
60
61
  /**
61
- * @description Setup queue and exchange if needed
62
+ * @description Setup queue and exchange if needed (call after connect when using exchanges)
62
63
  */
63
64
  async setup() {
64
65
  try {
65
66
  if (this.exchange) {
66
67
  // Create exchange
67
- await this.createExchange({
68
+ await this.rabbitMq.createExchange({
68
69
  name: this.exchange,
69
70
  type: 'direct',
70
71
  durable: true
71
72
  });
72
73
 
73
74
  // Create queue
74
- await this.createQueue({
75
+ await this.rabbitMq.createQueue({
75
76
  name: this.queue,
76
77
  durable: true
77
78
  });
78
79
 
79
80
  // Bind queue to exchange
80
- await this.bindQueue(this.queue, this.exchange, this.routingKey);
81
+ await this.rabbitMq.bindQueue(this.queue, this.exchange, this.routingKey);
81
82
  } else {
82
83
  // Create queue only
83
- await this.createQueue({
84
+ await this.rabbitMq.createQueue({
84
85
  name: this.queue,
85
86
  durable: true
86
87
  });
@@ -92,11 +93,13 @@ export class RabbitMQProducer extends RabbitMQManager implements IRabbitMQProduc
92
93
  }
93
94
 
94
95
  /**
95
- * @description Open Connection
96
+ * @description Ensure the underlying RabbitMQ manager is connected
96
97
  */
97
98
  async connect() {
98
99
  try {
99
- await super.connect();
100
+ if (!this.rabbitMq.isConnected()) {
101
+ await this.rabbitMq.connect();
102
+ }
100
103
  // await this.setup();
101
104
  } catch (error: any) {
102
105
  console.error('Failed to connect RabbitMQ Producer.', error);
@@ -105,9 +108,21 @@ export class RabbitMQProducer extends RabbitMQManager implements IRabbitMQProduc
105
108
  }
106
109
 
107
110
  /**
108
- * @description Close Connection
111
+ * @description Close connection only for a dedicated manager instance
112
+ * No-op when using the default `rabbitMQ` singleton (shared connection)
109
113
  */
110
114
  async disconnect() {
111
- await super.disconnect();
115
+ if (this.rabbitMq === rabbitMQ) {
116
+ return;
117
+ }
118
+ await this.rabbitMq.disconnect();
119
+ }
120
+
121
+ /**
122
+ * @description Get the RabbitMQ manager instance used by this producer
123
+ * @returns {RabbitMQManager} Composed manager
124
+ */
125
+ getRabbitMq(): RabbitMQManager {
126
+ return this.rabbitMq;
112
127
  }
113
128
  }
@@ -1,23 +1,40 @@
1
1
  import { IRabbitMQProducer } from '../interface';
2
+ import { getManagerPoolKey } from '../manager-key';
3
+ import { rabbitMQ, RabbitMQManager } from '../rabbitmq';
2
4
  import { RabbitMQProducer } from './producer.rabbitmq';
3
5
 
4
6
  /**
5
7
  * @description Producer service for managing multiple RabbitMQ producers
6
8
  * Maintains a pool of producers for different queue/exchange combinations
7
9
  */
8
- class ProducerService {
10
+ export class ProducerService {
9
11
  private readonly producers = new Map<string, IRabbitMQProducer>();
10
12
 
11
13
  /**
12
- * @description Publish Message to Queue/Exchange
13
- * @param {string} queue
14
- * @param {any} message
15
- * @param {string} exchange
16
- * @param {string} routingKey
14
+ * @description Optional default RabbitMQ manager when not passed per produce() call
15
+ * @param {RabbitMQManager} defaultRabbitMq - Falls back to package singleton `rabbitMQ` when omitted
17
16
  */
18
- async produce(queue: string, message: any, exchange?: string, routingKey?: string) {
17
+ constructor(private readonly defaultRabbitMq?: RabbitMQManager) {}
18
+
19
+ /**
20
+ * @description Publish message to queue/exchange
21
+ * Resolves manager: per-call `rabbitMq` → service default → singleton `rabbitMQ`
22
+ * @param {string} queue - Target queue name
23
+ * @param {any} message - Message payload
24
+ * @param {string} exchange - Optional exchange name
25
+ * @param {string} routingKey - Optional routing key when using an exchange
26
+ * @param {RabbitMQManager} rabbitMq - Optional manager override for this publish
27
+ */
28
+ async produce(
29
+ queue: string,
30
+ message: any,
31
+ exchange?: string,
32
+ routingKey?: string,
33
+ rabbitMq?: RabbitMQManager
34
+ ) {
19
35
  try {
20
- const producer = await this.getProducer(queue, exchange, routingKey);
36
+ const manager = rabbitMq ?? this.defaultRabbitMq ?? rabbitMQ;
37
+ const producer = await this.getProducer(queue, exchange, routingKey, manager);
21
38
  await producer.produce(message);
22
39
  console.info('RabbitMQ Producer Message Published :: ', message, queue);
23
40
  } catch (error: any) {
@@ -26,14 +43,30 @@ class ProducerService {
26
43
  }
27
44
 
28
45
  /**
29
- * @description Maintain a producer for each queue/exchange combination
30
- * @param {string} queue
31
- * @param {string} exchange
32
- * @param {string} routingKey
33
- * @returns
46
+ * @description Resolve RabbitMQ manager for producer pool and publish calls
47
+ * @param {RabbitMQManager} rabbitMq - Optional override
48
+ * @returns {RabbitMQManager} Resolved manager instance
49
+ */
50
+ private resolveManager(rabbitMq?: RabbitMQManager): RabbitMQManager {
51
+ return rabbitMq ?? this.defaultRabbitMq ?? rabbitMQ;
52
+ }
53
+
54
+ /**
55
+ * @description Maintain a producer for each manager + queue/exchange combination
56
+ * @param {string} queue - Queue name
57
+ * @param {string} exchange - Optional exchange name
58
+ * @param {string} routingKey - Optional routing key
59
+ * @param {RabbitMQManager} rabbitMq - Optional manager override
60
+ * @returns {Promise<IRabbitMQProducer>} Cached or newly created producer
34
61
  */
35
- private async getProducer(queue: string, exchange?: string, routingKey?: string) {
36
- const producerKey = `${queue}_${exchange || 'direct'}_${routingKey || ''}`;
62
+ private async getProducer(
63
+ queue: string,
64
+ exchange?: string,
65
+ routingKey?: string,
66
+ rabbitMq?: RabbitMQManager
67
+ ) {
68
+ const manager = this.resolveManager(rabbitMq);
69
+ const producerKey = `${getManagerPoolKey(manager)}_${queue}_${exchange || 'direct'}_${routingKey || ''}`;
37
70
  let producer = this.producers.get(producerKey);
38
71
 
39
72
  if (!producer) {
@@ -42,7 +75,8 @@ class ProducerService {
42
75
  exchange,
43
76
  routingKey,
44
77
  durable: true,
45
- persistent: true
78
+ persistent: true,
79
+ rabbitMq: manager
46
80
  });
47
81
  await producer.connect();
48
82
  this.producers.set(producerKey, producer);
@@ -52,7 +86,9 @@ class ProducerService {
52
86
  }
53
87
 
54
88
  /**
55
- * @description Disconnect all producers
89
+ * @description Disconnect all pooled producers
90
+ * Does not close the default `rabbitMQ` singleton connection.
91
+ * Call `rabbitMQ.disconnect()` at application shutdown to close the shared connection.
56
92
  */
57
93
  async disconnectAll() {
58
94
  for (const [key, producer] of this.producers) {
@@ -67,18 +103,21 @@ class ProducerService {
67
103
  }
68
104
 
69
105
  /**
70
- * @description Get producer count
106
+ * @description Get the number of producers in the pool
107
+ * @returns {number} Producer count
71
108
  */
72
109
  getProducerCount(): number {
73
110
  return this.producers.size;
74
111
  }
75
112
 
76
113
  /**
77
- * @description Get all producer keys
114
+ * @description Get all producer pool keys
115
+ * @returns {string[]} List of cache keys (manager + queue + exchange + routing key)
78
116
  */
79
117
  getProducerKeys(): string[] {
80
118
  return Array.from(this.producers.keys());
81
119
  }
82
120
  }
83
121
 
122
+ /** Pre-configured producer service singleton */
84
123
  export const producer = new ProducerService();
package/src/rabbitmq.ts CHANGED
@@ -6,18 +6,42 @@ import { IRabbitMQConfig, IQueueConfig, IExchangeConfig } from './interface';
6
6
  * Provides core functionality for connecting to RabbitMQ and managing queues and exchanges
7
7
  */
8
8
  export class RabbitMQManager {
9
+ private config: IRabbitMQConfig | null = null;
10
+
9
11
  protected connection: ChannelModel | null = null;
10
12
  protected channel: Channel | null = null;
11
- private config: IRabbitMQConfig;
12
13
 
13
14
  /**
14
- * @description Set RabbitMQ configuration
15
+ * @description Set RabbitMQ connection configuration for this instance
15
16
  * @param {IRabbitMQConfig} config - RabbitMQ connection configuration
16
17
  */
17
- setConfig(config: IRabbitMQConfig) {
18
+ setConfig(config: IRabbitMQConfig): void {
18
19
  this.config = config;
19
20
  }
20
21
 
22
+ /**
23
+ * @description Whether this instance has been configured via setConfig
24
+ */
25
+ isConfigured(): boolean {
26
+ return this.config !== null;
27
+ }
28
+
29
+ /**
30
+ * @description Connection URL when configured (for pool keys / debugging)
31
+ */
32
+ getUrl(): string | undefined {
33
+ return this.config?.url;
34
+ }
35
+
36
+ private getConfig(): IRabbitMQConfig {
37
+ if (!this.config) {
38
+ throw new Error(
39
+ 'RabbitMQ is not configured. Call setConfig({ url, connectionOptions }) on this RabbitMQManager instance first.'
40
+ );
41
+ }
42
+ return this.config;
43
+ }
44
+
21
45
  /**
22
46
  * @description Create the queue if it has not been already created.
23
47
  */
@@ -77,6 +101,13 @@ export class RabbitMQManager {
77
101
  }
78
102
  }
79
103
 
104
+ /**
105
+ * @description Get connection instance (null if not connected)
106
+ */
107
+ getConnection(): ChannelModel | null {
108
+ return this.connection;
109
+ }
110
+
80
111
  /**
81
112
  * @description Get channel instance
82
113
  */
@@ -92,10 +123,10 @@ export class RabbitMQManager {
92
123
  */
93
124
  async connect() {
94
125
  try {
95
- this.connection = <ChannelModel>await connect(this.config.url, this.config.connectionOptions);
126
+ const config = this.getConfig();
127
+ this.connection = <ChannelModel>await connect(config.url, config.connectionOptions);
96
128
  this.channel = await this.connection.createChannel();
97
129
 
98
- // Handle connection events
99
130
  this.connection.on('error', (error) => {
100
131
  console.error('RabbitMQ Connection Error:', error);
101
132
  });
@@ -146,3 +177,6 @@ export class RabbitMQManager {
146
177
  }
147
178
  }
148
179
  }
180
+
181
+ /** Default shared RabbitMQ manager for producer/consumer services */
182
+ export const rabbitMQ = new RabbitMQManager();