@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.
@@ -0,0 +1,113 @@
1
+ import { IRabbitMQProducer, IRabbitMQProducerOptions } from '../interface';
2
+ import { RabbitMQManager } from '../rabbitmq';
3
+
4
+ /**
5
+ * @description RabbitMQ producer class for publishing messages to queues or exchanges
6
+ * Extends RabbitMQManager to provide message publishing functionality
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;
13
+
14
+ /**
15
+ * @description Initialize RabbitMQ producer with configuration
16
+ * @param {IRabbitMQProducerOptions} options - Producer configuration options
17
+ */
18
+ constructor(options: IRabbitMQProducerOptions) {
19
+ super();
20
+ this.queue = options.queue;
21
+ this.exchange = options.exchange;
22
+ this.routingKey = options.routingKey || '';
23
+ this.persistent = options.persistent ?? true;
24
+ }
25
+
26
+ /**
27
+ * @description Publish Message to RabbitMQ Queue/Exchange
28
+ * @param {any} message
29
+ */
30
+ async produce(message: any) {
31
+ try {
32
+ if (!this.isConnected()) {
33
+ await this.reconnect();
34
+ }
35
+
36
+ const channel = this.getChannel();
37
+ const messageBuffer = Buffer.from(JSON.stringify(message));
38
+
39
+ if (this.exchange) {
40
+ // Publish to exchange
41
+ channel.publish(this.exchange, this.routingKey || '', messageBuffer, {
42
+ persistent: this.persistent,
43
+ timestamp: Date.now()
44
+ });
45
+ console.info(`Message published to exchange: ${this.exchange}, routing key: ${this.routingKey}`);
46
+ } else {
47
+ // Publish directly to queue
48
+ channel.sendToQueue(this.queue, messageBuffer, {
49
+ persistent: this.persistent,
50
+ timestamp: Date.now()
51
+ });
52
+ console.info(`Message published to queue: ${this.queue}`);
53
+ }
54
+ } catch (error: any) {
55
+ console.error(`Error publishing message to RabbitMQ: `, error);
56
+ throw error;
57
+ }
58
+ }
59
+
60
+ /**
61
+ * @description Setup queue and exchange if needed
62
+ */
63
+ async setup() {
64
+ try {
65
+ if (this.exchange) {
66
+ // Create exchange
67
+ await this.createExchange({
68
+ name: this.exchange,
69
+ type: 'direct',
70
+ durable: true
71
+ });
72
+
73
+ // Create queue
74
+ await this.createQueue({
75
+ name: this.queue,
76
+ durable: true
77
+ });
78
+
79
+ // Bind queue to exchange
80
+ await this.bindQueue(this.queue, this.exchange, this.routingKey);
81
+ } else {
82
+ // Create queue only
83
+ await this.createQueue({
84
+ name: this.queue,
85
+ durable: true
86
+ });
87
+ }
88
+ } catch (error: any) {
89
+ console.error(`Error setting up RabbitMQ producer: `, error);
90
+ throw error;
91
+ }
92
+ }
93
+
94
+ /**
95
+ * @description Open Connection
96
+ */
97
+ async connect() {
98
+ try {
99
+ await super.connect();
100
+ // await this.setup();
101
+ } catch (error: any) {
102
+ console.error('Failed to connect RabbitMQ Producer.', error);
103
+ throw error;
104
+ }
105
+ }
106
+
107
+ /**
108
+ * @description Close Connection
109
+ */
110
+ async disconnect() {
111
+ await super.disconnect();
112
+ }
113
+ }
@@ -0,0 +1,84 @@
1
+ import { IRabbitMQProducer } from '../interface';
2
+ import { RabbitMQProducer } from './producer.rabbitmq';
3
+
4
+ /**
5
+ * @description Producer service for managing multiple RabbitMQ producers
6
+ * Maintains a pool of producers for different queue/exchange combinations
7
+ */
8
+ class ProducerService {
9
+ private readonly producers = new Map<string, IRabbitMQProducer>();
10
+
11
+ /**
12
+ * @description Publish Message to Queue/Exchange
13
+ * @param {string} queue
14
+ * @param {any} message
15
+ * @param {string} exchange
16
+ * @param {string} routingKey
17
+ */
18
+ async produce(queue: string, message: any, exchange?: string, routingKey?: string) {
19
+ try {
20
+ const producer = await this.getProducer(queue, exchange, routingKey);
21
+ await producer.produce(message);
22
+ console.info('RabbitMQ Producer Message Published :: ', message, queue);
23
+ } catch (error: any) {
24
+ console.error(`Error--RabbitMQ produce--msg ::`, error);
25
+ }
26
+ }
27
+
28
+ /**
29
+ * @description Maintain a producer for each queue/exchange combination
30
+ * @param {string} queue
31
+ * @param {string} exchange
32
+ * @param {string} routingKey
33
+ * @returns
34
+ */
35
+ private async getProducer(queue: string, exchange?: string, routingKey?: string) {
36
+ const producerKey = `${queue}_${exchange || 'direct'}_${routingKey || ''}`;
37
+ let producer = this.producers.get(producerKey);
38
+
39
+ if (!producer) {
40
+ producer = new RabbitMQProducer({
41
+ queue,
42
+ exchange,
43
+ routingKey,
44
+ durable: true,
45
+ persistent: true
46
+ });
47
+ await producer.connect();
48
+ this.producers.set(producerKey, producer);
49
+ }
50
+
51
+ return producer;
52
+ }
53
+
54
+ /**
55
+ * @description Disconnect all producers
56
+ */
57
+ async disconnectAll() {
58
+ for (const [key, producer] of this.producers) {
59
+ try {
60
+ await producer.disconnect();
61
+ console.info(`Disconnected producer: ${key}`);
62
+ } catch (error: any) {
63
+ console.error(`Error disconnecting producer ${key}:`, error);
64
+ }
65
+ }
66
+ this.producers.clear();
67
+ }
68
+
69
+ /**
70
+ * @description Get producer count
71
+ */
72
+ getProducerCount(): number {
73
+ return this.producers.size;
74
+ }
75
+
76
+ /**
77
+ * @description Get all producer keys
78
+ */
79
+ getProducerKeys(): string[] {
80
+ return Array.from(this.producers.keys());
81
+ }
82
+ }
83
+
84
+ export const producer = new ProducerService();
@@ -0,0 +1,148 @@
1
+ import { connect, ChannelModel, Channel } from 'amqplib';
2
+ import { IRabbitMQConfig, IQueueConfig, IExchangeConfig } from './interface';
3
+
4
+ /**
5
+ * @description Base RabbitMQ manager class for connection and queue/exchange management
6
+ * Provides core functionality for connecting to RabbitMQ and managing queues and exchanges
7
+ */
8
+ export class RabbitMQManager {
9
+ protected connection: ChannelModel | null = null;
10
+ protected channel: Channel | null = null;
11
+ private config: IRabbitMQConfig;
12
+
13
+ /**
14
+ * @description Set RabbitMQ configuration
15
+ * @param {IRabbitMQConfig} config - RabbitMQ connection configuration
16
+ */
17
+ setConfig(config: IRabbitMQConfig) {
18
+ this.config = config;
19
+ }
20
+
21
+ /**
22
+ * @description Create the queue if it has not been already created.
23
+ */
24
+ async createQueue(queueConfig: IQueueConfig) {
25
+ try {
26
+ if (!this.channel) {
27
+ throw new Error('Channel not initialized');
28
+ }
29
+
30
+ await this.channel.assertQueue(queueConfig.name, {
31
+ durable: queueConfig.durable ?? true,
32
+ exclusive: queueConfig.exclusive ?? false,
33
+ autoDelete: queueConfig.autoDelete ?? false,
34
+ arguments: queueConfig.arguments
35
+ });
36
+
37
+ console.info('RabbitMQ Queue Created ::', queueConfig.name);
38
+ } catch (error) {
39
+ console.error('RabbitMQ Error Queue Creation', error);
40
+ }
41
+ }
42
+
43
+ /**
44
+ * @description Create the exchange if it has not been already created.
45
+ */
46
+ async createExchange(exchangeConfig: IExchangeConfig) {
47
+ try {
48
+ if (!this.channel) {
49
+ throw new Error('Channel not initialized');
50
+ }
51
+
52
+ await this.channel.assertExchange(exchangeConfig.name, exchangeConfig.type, {
53
+ durable: exchangeConfig.durable ?? true,
54
+ autoDelete: exchangeConfig.autoDelete ?? false,
55
+ arguments: exchangeConfig.arguments
56
+ });
57
+
58
+ console.info('RabbitMQ Exchange Created ::', exchangeConfig.name);
59
+ } catch (error) {
60
+ console.error('RabbitMQ Error Exchange Creation', error);
61
+ }
62
+ }
63
+
64
+ /**
65
+ * @description Bind queue to exchange
66
+ */
67
+ async bindQueue(queueName: string, exchangeName: string, routingKey: string = '') {
68
+ try {
69
+ if (!this.channel) {
70
+ throw new Error('Channel not initialized');
71
+ }
72
+
73
+ await this.channel.bindQueue(queueName, exchangeName, routingKey);
74
+ console.info(`RabbitMQ Queue ${queueName} bound to exchange ${exchangeName} with routing key ${routingKey}`);
75
+ } catch (error) {
76
+ console.error('RabbitMQ Error Binding Queue', error);
77
+ }
78
+ }
79
+
80
+ /**
81
+ * @description Get channel instance
82
+ */
83
+ getChannel(): Channel {
84
+ if (!this.channel) {
85
+ throw new Error('Channel not initialized');
86
+ }
87
+ return this.channel;
88
+ }
89
+
90
+ /**
91
+ * @description Open Connection
92
+ */
93
+ async connect() {
94
+ try {
95
+ this.connection = <ChannelModel>await connect(this.config.url, this.config.connectionOptions);
96
+ this.channel = await this.connection.createChannel();
97
+
98
+ // Handle connection events
99
+ this.connection.on('error', (error) => {
100
+ console.error('RabbitMQ Connection Error:', error);
101
+ });
102
+
103
+ this.connection.on('close', () => {
104
+ console.warn('RabbitMQ Connection Closed');
105
+ });
106
+
107
+ console.info('Connected to RabbitMQ successfully');
108
+ } catch (error) {
109
+ console.error('Failed to connect to RabbitMQ.', error);
110
+ throw error;
111
+ }
112
+ }
113
+
114
+ /**
115
+ * @description Close Connection
116
+ */
117
+ async disconnect() {
118
+ try {
119
+ if (this.channel) {
120
+ await this.channel.close();
121
+ this.channel = null;
122
+ }
123
+ if (this.connection) {
124
+ await this.connection.close();
125
+ this.connection = null;
126
+ }
127
+ console.info('Disconnected from RabbitMQ');
128
+ } catch (error) {
129
+ console.error('Error disconnecting from RabbitMQ:', error);
130
+ }
131
+ }
132
+
133
+ /**
134
+ * @description Check if connection is alive
135
+ */
136
+ isConnected(): boolean {
137
+ return this.connection !== null;
138
+ }
139
+
140
+ /**
141
+ * @description Reconnect if connection is lost
142
+ */
143
+ async reconnect() {
144
+ if (!this.isConnected()) {
145
+ await this.connect();
146
+ }
147
+ }
148
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "compilerOptions": {
3
+ "declaration": true,
4
+ "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
5
+ "module": "commonjs",
6
+ "incremental": true,
7
+ "noEmit": false, /* Specify what module code is generated. */
8
+ "outDir": "./dist", /* Specify an output folder for all emitted files. */
9
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
10
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
11
+ "strict": true, /* Enable all strict type-checking options. */
12
+ "skipLibCheck": true, /* Skip type checking all .d.ts files. */
13
+ "strictPropertyInitialization": false, /* Check for class properties that are declared but not set in the constructor. */
14
+ "sourceMap": true, /* Create source map files for emitted JavaScript files. */
15
+ "resolveJsonModule": true,
16
+ "experimentalDecorators": true,
17
+ "emitDecoratorMetadata": true,
18
+ "baseUrl": ".",
19
+ }
20
+ }