@appinventiv/rabbit-mq 1.0.2 → 1.0.5

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,22 +1,24 @@
1
+ import { fetchErrorMessage } from 'src/manager-key';
1
2
  import { IRabbitMQProducer, IRabbitMQProducerOptions } from '../interface';
2
- import { RabbitMQManager } from '../rabbitmq';
3
+ import { rabbitMQ, RabbitMQManager } from '../rabbitmq';
3
4
 
4
5
  /**
5
6
  * @description RabbitMQ producer class for publishing messages to queues or exchanges
6
- * Extends RabbitMQManager to provide message publishing functionality
7
+ * Uses a composed RabbitMQManager instance (default: package singleton `rabbitMQ`)
7
8
  */
8
- export class RabbitMQProducer extends RabbitMQManager implements IRabbitMQProducer {
9
- private queue: string;
10
- private exchange?: string;
11
- private routingKey?: string;
12
- private persistent: boolean;
9
+ export class RabbitMQProducer implements IRabbitMQProducer {
10
+ private readonly rabbitMq: RabbitMQManager;
11
+ private readonly queue: string;
12
+ private readonly exchange?: string;
13
+ private readonly routingKey?: string;
14
+ private readonly persistent: boolean;
13
15
 
14
16
  /**
15
17
  * @description Initialize RabbitMQ producer with configuration
16
- * @param {IRabbitMQProducerOptions} options - Producer configuration options
18
+ * @param {IRabbitMQProducerOptions} options - Producer configuration options (queue, exchange, routing key, optional `rabbitMq`)
17
19
  */
18
20
  constructor(options: IRabbitMQProducerOptions) {
19
- super();
21
+ this.rabbitMq = options.rabbitMq ?? rabbitMQ;
20
22
  this.queue = options.queue;
21
23
  this.exchange = options.exchange;
22
24
  this.routingKey = options.routingKey || '';
@@ -24,20 +26,20 @@ export class RabbitMQProducer extends RabbitMQManager implements IRabbitMQProduc
24
26
  }
25
27
 
26
28
  /**
27
- * @description Publish Message to RabbitMQ Queue/Exchange
28
- * @param {any} message
29
+ * @description Publish message to RabbitMQ queue or exchange
30
+ * @param {any} message - Payload serialized as JSON
29
31
  */
30
32
  async produce(message: any) {
31
33
  try {
32
- if (!this.isConnected()) {
33
- await this.reconnect();
34
+ if (!this.rabbitMq.isConnected()) {
35
+ await this.rabbitMq.reconnect();
34
36
  }
35
37
 
36
- const channel = this.getChannel();
38
+ const channel = this.rabbitMq.getChannel();
37
39
  const messageBuffer = Buffer.from(JSON.stringify(message));
38
40
 
39
41
  if (this.exchange) {
40
- // Publish to exchange
42
+ // Publish to exchange with routing key
41
43
  channel.publish(this.exchange, this.routingKey || '', messageBuffer, {
42
44
  persistent: this.persistent,
43
45
  timestamp: Date.now()
@@ -52,62 +54,76 @@ export class RabbitMQProducer extends RabbitMQManager implements IRabbitMQProduc
52
54
  console.info(`Message published to queue: ${this.queue}`);
53
55
  }
54
56
  } catch (error: any) {
55
- console.error(`Error publishing message to RabbitMQ: `, error);
57
+ console.error(`Error publishing message to RabbitMQ: ${fetchErrorMessage(error)}`);
56
58
  throw error;
57
59
  }
58
60
  }
59
61
 
60
62
  /**
61
- * @description Setup queue and exchange if needed
63
+ * @description Setup queue and exchange if needed (call after connect when using exchanges)
62
64
  */
63
65
  async setup() {
64
66
  try {
65
67
  if (this.exchange) {
66
68
  // Create exchange
67
- await this.createExchange({
69
+ await this.rabbitMq.createExchange({
68
70
  name: this.exchange,
69
71
  type: 'direct',
70
72
  durable: true
71
73
  });
72
74
 
73
75
  // Create queue
74
- await this.createQueue({
76
+ await this.rabbitMq.createQueue({
75
77
  name: this.queue,
76
78
  durable: true
77
79
  });
78
80
 
79
81
  // Bind queue to exchange
80
- await this.bindQueue(this.queue, this.exchange, this.routingKey);
82
+ await this.rabbitMq.bindQueue(this.queue, this.exchange, this.routingKey);
81
83
  } else {
82
84
  // Create queue only
83
- await this.createQueue({
85
+ await this.rabbitMq.createQueue({
84
86
  name: this.queue,
85
87
  durable: true
86
88
  });
87
89
  }
88
90
  } catch (error: any) {
89
- console.error(`Error setting up RabbitMQ producer: `, error);
91
+ console.error(`Error setting up RabbitMQ producer: ${fetchErrorMessage(error)}`);
90
92
  throw error;
91
93
  }
92
94
  }
93
95
 
94
96
  /**
95
- * @description Open Connection
97
+ * @description Ensure the underlying RabbitMQ manager is connected
96
98
  */
97
99
  async connect() {
98
100
  try {
99
- await super.connect();
101
+ if (!this.rabbitMq.isConnected()) {
102
+ await this.rabbitMq.connect();
103
+ }
100
104
  // await this.setup();
101
105
  } catch (error: any) {
102
- console.error('Failed to connect RabbitMQ Producer.', error);
106
+ console.error(`Failed to connect RabbitMQ Producer. ${fetchErrorMessage(error)}`);
103
107
  throw error;
104
108
  }
105
109
  }
106
110
 
107
111
  /**
108
- * @description Close Connection
112
+ * @description Close connection only for a dedicated manager instance
113
+ * No-op when using the default `rabbitMQ` singleton (shared connection)
109
114
  */
110
115
  async disconnect() {
111
- await super.disconnect();
116
+ if (this.rabbitMq === rabbitMQ) {
117
+ return;
118
+ }
119
+ await this.rabbitMq.disconnect();
120
+ }
121
+
122
+ /**
123
+ * @description Get the RabbitMQ manager instance used by this producer
124
+ * @returns {RabbitMQManager} Composed manager
125
+ */
126
+ getRabbitMq(): RabbitMQManager {
127
+ return this.rabbitMq;
112
128
  }
113
129
  }
@@ -1,39 +1,72 @@
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
- console.info('RabbitMQ Producer Message Published :: ', message, queue);
39
+ console.info(`RabbitMQ Producer Message Published :: ${queue}`);
23
40
  } catch (error: any) {
24
- console.error(`Error--RabbitMQ produce--msg ::`, error);
41
+ throw error;
25
42
  }
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
@@ -1,23 +1,48 @@
1
1
  import { connect, ChannelModel, Channel } from 'amqplib';
2
2
  import { IRabbitMQConfig, IQueueConfig, IExchangeConfig } from './interface';
3
+ import { fetchErrorMessage } from './manager-key';
3
4
 
4
5
  /**
5
6
  * @description Base RabbitMQ manager class for connection and queue/exchange management
6
7
  * Provides core functionality for connecting to RabbitMQ and managing queues and exchanges
7
8
  */
8
9
  export class RabbitMQManager {
10
+ private config: IRabbitMQConfig | null = null;
11
+
9
12
  protected connection: ChannelModel | null = null;
10
13
  protected channel: Channel | null = null;
11
- private config: IRabbitMQConfig;
12
14
 
13
15
  /**
14
- * @description Set RabbitMQ configuration
16
+ * @description Set RabbitMQ connection configuration for this instance
15
17
  * @param {IRabbitMQConfig} config - RabbitMQ connection configuration
16
18
  */
17
- setConfig(config: IRabbitMQConfig) {
19
+ setConfig(config: IRabbitMQConfig): void {
18
20
  this.config = config;
19
21
  }
20
22
 
23
+ /**
24
+ * @description Whether this instance has been configured via setConfig
25
+ */
26
+ isConfigured(): boolean {
27
+ return this.config !== null;
28
+ }
29
+
30
+ /**
31
+ * @description Connection URL when configured (for pool keys / debugging)
32
+ */
33
+ getUrl(): string | undefined {
34
+ return this.config?.url;
35
+ }
36
+
37
+ private getConfig(): IRabbitMQConfig {
38
+ if (!this.config) {
39
+ throw new Error(
40
+ 'RabbitMQ is not configured. Call setConfig({ url, connectionOptions }) on this RabbitMQManager instance first.'
41
+ );
42
+ }
43
+ return this.config;
44
+ }
45
+
21
46
  /**
22
47
  * @description Create the queue if it has not been already created.
23
48
  */
@@ -36,7 +61,7 @@ export class RabbitMQManager {
36
61
 
37
62
  console.info('RabbitMQ Queue Created ::', queueConfig.name);
38
63
  } catch (error) {
39
- console.error('RabbitMQ Error Queue Creation', error);
64
+ console.error(`RabbitMQ Error Queue Creation ${fetchErrorMessage(error)}`);
40
65
  }
41
66
  }
42
67
 
@@ -57,7 +82,7 @@ export class RabbitMQManager {
57
82
 
58
83
  console.info('RabbitMQ Exchange Created ::', exchangeConfig.name);
59
84
  } catch (error) {
60
- console.error('RabbitMQ Error Exchange Creation', error);
85
+ console.error(`RabbitMQ Error Exchange Creation ${fetchErrorMessage(error)}`);
61
86
  }
62
87
  }
63
88
 
@@ -73,10 +98,17 @@ export class RabbitMQManager {
73
98
  await this.channel.bindQueue(queueName, exchangeName, routingKey);
74
99
  console.info(`RabbitMQ Queue ${queueName} bound to exchange ${exchangeName} with routing key ${routingKey}`);
75
100
  } catch (error) {
76
- console.error('RabbitMQ Error Binding Queue', error);
101
+ console.error(`RabbitMQ Error Binding Queue ${fetchErrorMessage(error)}`);
77
102
  }
78
103
  }
79
104
 
105
+ /**
106
+ * @description Get connection instance (null if not connected)
107
+ */
108
+ getConnection(): ChannelModel | null {
109
+ return this.connection;
110
+ }
111
+
80
112
  /**
81
113
  * @description Get channel instance
82
114
  */
@@ -92,10 +124,10 @@ export class RabbitMQManager {
92
124
  */
93
125
  async connect() {
94
126
  try {
95
- this.connection = <ChannelModel>await connect(this.config.url, this.config.connectionOptions);
127
+ const config = this.getConfig();
128
+ this.connection = <ChannelModel>await connect(config.url, config.connectionOptions);
96
129
  this.channel = await this.connection.createChannel();
97
130
 
98
- // Handle connection events
99
131
  this.connection.on('error', (error) => {
100
132
  console.error('RabbitMQ Connection Error:', error);
101
133
  });
@@ -106,7 +138,7 @@ export class RabbitMQManager {
106
138
 
107
139
  console.info('Connected to RabbitMQ successfully');
108
140
  } catch (error) {
109
- console.error('Failed to connect to RabbitMQ.', error);
141
+ console.error(`Failed to connect to RabbitMQ. ${fetchErrorMessage(error)}`);
110
142
  throw error;
111
143
  }
112
144
  }
@@ -126,7 +158,8 @@ export class RabbitMQManager {
126
158
  }
127
159
  console.info('Disconnected from RabbitMQ');
128
160
  } catch (error) {
129
- console.error('Error disconnecting from RabbitMQ:', error);
161
+ console.error(`Error disconnecting from RabbitMQ: ${fetchErrorMessage(error)}`);
162
+ throw error;
130
163
  }
131
164
  }
132
165
 
@@ -146,3 +179,6 @@ export class RabbitMQManager {
146
179
  }
147
180
  }
148
181
  }
182
+
183
+ /** Default shared RabbitMQ manager for producer/consumer services */
184
+ export const rabbitMQ = new RabbitMQManager();