rxjs-rabbitmq 2.1.9 → 2.2.1

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 CHANGED
@@ -1,99 +1,450 @@
1
1
  # RxJS RabbitMQ Client
2
2
 
3
+ A lightweight RabbitMQ client for Node.js that blends RabbitMQ messaging with RxJS-style event handling.
3
4
 
5
+ The library is intentionally small and stable: it focuses on four primary tasks:
4
6
 
5
- ```typescript
6
- import {
7
- RabbitMQClient,
8
- RmqEventMessage
9
- } from "rxjs-rabbitmq";
10
-
11
- const handleMessageTypes: string[] = [
12
- ClientsQueueMessageTypes.ADD_CLIENT,
13
- UsersQueueEventTypes.USER_CREATED,
14
- UsersQueueEventTypes.USER_DELETED,
15
- AuthoritiesQueueEventTypes.AUTHORITY_CREATED,
16
- AuthoritiesQueueEventTypes.AUTHORITY_DELETED,
7
+ - establishing a RabbitMQ connection and channel
8
+ - asserting queues, exchanges, and bindings
9
+ - exposing queue events as RxJS streams
10
+ - supporting basic request/reply messaging and typed publish helpers
11
+
12
+ It is designed for service-to-service messaging where you want a simple and familiar RxJS interface without introducing a larger messaging framework.
13
+
14
+ ## Why this library exists
15
+
16
+ This package is best when you want:
17
+
18
+ - RabbitMQ message handling with RxJS streams
19
+ - per-queue event subscriptions
20
+ - message type routing from `message.properties.type`
21
+ - simple request/reply patterns
22
+ - direct control over RabbitMQ resources without a heavy abstraction layer
23
+
24
+ It is not a full orchestration engine or a replacement for a full enterprise messaging platform. The library tries to stay small, explicit, and operationally predictable.
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ npm install rxjs-rabbitmq amqplib rxjs uuid
30
+ ```
31
+
32
+ ## Core concepts
33
+
34
+ ### Queue configuration
35
+
36
+ Each configured queue can optionally declare known message types:
37
+
38
+ ```ts
39
+ const queues = [
40
+ {
41
+ name: 'emails',
42
+ handleMessageTypes: ['SEND_EMAIL', 'EMAIL_SENT'],
43
+ options: { durable: true }
44
+ }
17
45
  ];
46
+ ```
47
+
48
+ When a message arrives:
49
+
50
+ - the global `onMessage` stream receives it
51
+ - the queue-specific stream receives it
52
+ - if the message has a known `type`, it is routed to the matching registered stream or callback
53
+ - if no type is found, it is routed to the default queue handler when enabled
18
54
 
19
- const rmqClient = new RabbitMQClient({
20
- connection_url: AppEnvironment.RABBIT_MQ_URL,
21
- delayStart: 5000,
22
- prefetch: 5,
55
+ ### Exchange configuration
56
+
57
+ ```ts
58
+ const exchanges = [
59
+ {
60
+ name: 'user.events',
61
+ type: 'fanout',
62
+ options: { durable: true }
63
+ }
64
+ ];
65
+ ```
66
+
67
+ ### Binding configuration
68
+
69
+ ```ts
70
+ const bindings = [
71
+ {
72
+ queue: 'emails',
73
+ exchange: 'user.events',
74
+ routingKey: '#'
75
+ }
76
+ ];
77
+ ```
78
+
79
+ ## Quick start
80
+
81
+ ```ts
82
+ import { RabbitMQClient, RmqEventMessage, ContentTypes } from 'rxjs-rabbitmq';
83
+
84
+ const client = new RabbitMQClient({
85
+ connection_url: process.env.RABBITMQ_URL!,
23
86
  retryAttempts: 3,
24
- retryDelay: 3000,
87
+ retryDelay: 2000,
88
+ prefetch: 10,
25
89
  autoAckUnhandledMessageTypes: true,
26
90
  queues: [
27
- { name: MicroservicesQueues.EMAILS, handleMessageTypes, options: { durable: true } },
91
+ {
92
+ name: 'emails',
93
+ handleMessageTypes: ['SEND_EMAIL'],
94
+ options: { durable: true }
95
+ }
28
96
  ],
29
97
  exchanges: [
30
- { name: MicroservicesExchanges.EMAIL_EVENTS, type: 'fanout', options: { durable: true } },
31
- { name: MicroservicesExchanges.USER_EVENTS, type: 'fanout', options: { durable: true } },
32
- { name: MicroservicesExchanges.AUTHORITY_EVENTS, type: 'fanout', options: { durable: true } },
98
+ {
99
+ name: 'app.events',
100
+ type: 'fanout',
101
+ options: { durable: true }
102
+ }
33
103
  ],
34
- bindings: [
35
- { queue: MicroservicesQueues.EMAILS, exchange: MicroservicesExchanges.USER_EVENTS, routingKey: RoutingKeys.EVENT },
36
- { queue: MicroservicesQueues.EMAILS, exchange: MicroservicesExchanges.AUTHORITY_EVENTS, routingKey: RoutingKeys.EVENT },
37
- ]
104
+ bindings: []
38
105
  });
39
106
 
107
+ client.onMessage.subscribe((event: RmqEventMessage) => {
108
+ console.log('Received message', event.data);
109
+ });
40
110
 
41
- // Listen to all messages from a queue
42
- rmqClient.forQueue(MicroservicesQueues.NOTIFICATIONS).subscribe({
111
+ client.onQueue('emails').handle('SEND_EMAIL').subscribe({
43
112
  next: (event: RmqEventMessage) => {
44
- const handler: RmqEventHandler = EventHandlersMap[event.message.properties.type];
45
- if (!!handler && typeof (handler) === 'function') {
46
- handler(event);
113
+ console.log('Email event payload:', event.data);
114
+ event.ack();
115
+ }
116
+ });
117
+ ```
118
+
119
+ ## Event handling patterns
120
+
121
+ ### 1. Listen to every message on a queue
122
+
123
+ ```ts
124
+ const queue$ = client.forQueue('emails');
125
+
126
+ queue$.subscribe({
127
+ next: (event) => {
128
+ console.log('event payload', event.data);
129
+ }
130
+ });
131
+ ```
132
+
133
+ ### 2. Handle a specific message type
134
+
135
+ ```ts
136
+ const emailsQueue = client.onQueue('emails');
137
+
138
+ emailsQueue.handle('SEND_EMAIL').subscribe({
139
+ next: (event) => {
140
+ console.log(event.data);
141
+ event.ack();
142
+ }
143
+ });
144
+ ```
145
+
146
+ ### 3. Use a callback-based event handler
147
+
148
+ ```ts
149
+ const emailsQueue = client.onQueue('emails');
150
+
151
+ emailsQueue.onEvent('SEND_EMAIL', (event) => {
152
+ console.log(event.data);
153
+ event.ack();
154
+ });
155
+ ```
156
+
157
+ ### 4. Listen to all messages on a queue with a custom handler
158
+
159
+ ```ts
160
+ client.onQueue('emails').handleAll((event) => {
161
+ console.log(event.message.properties.type, event.data);
162
+ });
163
+ ```
164
+
165
+ ## Publishing messages
166
+
167
+ ### Publish to a queue
168
+
169
+ ```ts
170
+ client.sendMessage({
171
+ queue: 'emails',
172
+ data: { to: 'user@example.com', body: 'Hello' },
173
+ publishOptions: {
174
+ contentType: 'application/json',
175
+ persistent: true
176
+ }
177
+ });
178
+ ```
179
+
180
+ ### Publish to an exchange
181
+
182
+ ```ts
183
+ client.publishEvent({
184
+ exchange: 'app.events',
185
+ routingKey: 'user.created',
186
+ data: { id: '123', name: 'Ada' },
187
+ publishOptions: {
188
+ contentType: 'application/json',
189
+ type: 'USER_CREATED',
190
+ persistent: true
191
+ }
192
+ });
193
+ ```
194
+
195
+ ## Request/reply pattern
196
+
197
+ ```ts
198
+ const response = await client.sendRequest<{ ok: boolean }>({
199
+ queue: 'worker',
200
+ data: { action: 'generate-report' },
201
+ publishOptions: {
202
+ correlationId: 'req-123',
203
+ contentType: 'application/json',
204
+ type: 'GENERATE_REPORT'
205
+ }
206
+ }, true, 30000);
207
+
208
+ console.log(response.data);
209
+ ```
210
+
211
+ The request helper creates a temporary exclusive reply queue and watches for a matching correlation ID. If a reply is not received before the timeout, the promise rejects and the temporary consumer is cancelled.
212
+
213
+ ## Message acknowledgement and recovery
214
+
215
+ The event object includes helper methods:
216
+
217
+ ```ts
218
+ client.onQueue('emails').handle('SEND_EMAIL').subscribe({
219
+ next: (event) => {
220
+ // ack once business logic succeeds
221
+ event.ack();
222
+
223
+ // or reject and requeue if necessary
224
+ client.nack(event.message, true);
225
+ }
226
+ });
227
+ ```
228
+
229
+ ### Retry and dead-letter helpers
230
+
231
+ ```ts
232
+ client.onQueue('emails').handle('SEND_EMAIL').subscribe({
233
+ next: (event) => {
234
+ try {
235
+ // business logic
236
+ } catch (error) {
237
+ client.retryMessage(event.message, {
238
+ delayMs: 1000,
239
+ requeue: true,
240
+ queue: 'emails.retry'
241
+ });
47
242
  }
48
243
  }
49
244
  });
245
+ ```
246
+
247
+ ```ts
248
+ client.deadLetter(event.message, 'processing failed', 'emails.dlq');
249
+ ```
50
250
 
251
+ These helpers are intentionally opt-in and explicit; they avoid forcing a policy onto all consumers.
51
252
 
253
+ ## Serialization
52
254
 
53
- // Handle specific queue
54
- const emailsQueue = rmqClient.onQueue(MicroservicesQueues.EMAILS);
255
+ The library includes a built-in serializer registry in `SERIALIZERS` and supports custom registration.
55
256
 
56
- // Handle specific message types from a queue
57
- emailsQueue.handle(EmailsQueueMessageTypes.SEND_EMAIL).subscribe({ next: SEND_EMAIL });
257
+ ```ts
258
+ import { registerSerializer } from 'rxjs-rabbitmq';
58
259
 
59
- // shorthand/auto-subscribe and handle
60
- emailsQueue.onEvent(EmailsQueueMessageTypes.SEND_EMAIL, SEND_EMAIL);
260
+ registerSerializer('application/custom', {
261
+ serialize: (value) => Buffer.from(JSON.stringify(value)),
262
+ deserialize: (buffer) => JSON.parse(buffer.toString('utf8'))
263
+ });
264
+ ```
265
+
266
+ You can also call:
61
267
 
268
+ ```ts
269
+ RabbitMQClient.registerSerializer('application/custom', {
270
+ serialize: ...,
271
+ deserialize: ...
272
+ });
273
+ ```
62
274
 
275
+ ## Metrics and observability
63
276
 
64
- // event handler
277
+ When `metrics: true` is enabled, the client tracks counts for:
65
278
 
66
- export async function SEND_EMAIL(event: RmqEventMessage) {
67
- console.log(`[${EmailsQueueMessageTypes.SEND_EMAIL}] Received message:`, { data: event.data });
279
+ - received messages
280
+ - published messages
281
+ - acked messages
282
+ - nacked messages
283
+ - retried messages
284
+ - RPC requests
285
+ - RPC responses
286
+ - reconnects
68
287
 
69
- const sendEmailParams = event.data as SendEmailDto;
288
+ ```ts
289
+ const client = new RabbitMQClient({
290
+ connection_url: process.env.RABBITMQ_URL!,
291
+ metrics: true,
292
+ queues: [],
293
+ exchanges: [],
294
+ bindings: [],
295
+ retryAttempts: 2,
296
+ retryDelay: 1000
297
+ });
70
298
 
71
- const email_send_results: SendEmailCommandOutput = await sendAwsEmail({
72
- to: sendEmailParams.to_email,
73
- subject: sendEmailParams.subject,
74
- message: sendEmailParams.text,
75
- html: sendEmailParams.html,
76
- });
299
+ console.log(client.getMetrics());
300
+ ```
301
+
302
+ This is useful for diagnostics and operational visibility, but it remains optional and should not be enabled unless you want the extra bookkeeping.
303
+
304
+ ## Logger configuration
305
+
306
+ Logs are optional and fully configurable.
307
+
308
+ ```ts
309
+ const client = new RabbitMQClient({
310
+ connection_url: process.env.RABBITMQ_URL!,
311
+ logger: {
312
+ debug: (...args) => console.debug('[rabbitmq]', ...args),
313
+ info: (...args) => console.info('[rabbitmq]', ...args),
314
+ warn: (...args) => console.warn('[rabbitmq]', ...args),
315
+ error: (...args) => console.error('[rabbitmq]', ...args)
316
+ },
317
+ queues: [],
318
+ exchanges: [],
319
+ bindings: [],
320
+ retryAttempts: 3,
321
+ retryDelay: 2000
322
+ });
323
+ ```
324
+
325
+ This is especially helpful in production, where per-message logs can become a throughput bottleneck.
326
+
327
+ ## Lifecycle management
328
+
329
+ The client exposes a manual close method for clean shutdown:
330
+
331
+ ```ts
332
+ await client.close();
333
+ ```
334
+
335
+ This clears any reconnect timer, closes the channel and connection, and marks the client as no longer ready.
336
+
337
+ ## Full example
338
+
339
+ ```ts
340
+ import {
341
+ RabbitMQClient,
342
+ RmqEventMessage,
343
+ ContentTypes
344
+ } from 'rxjs-rabbitmq';
77
345
 
78
- const serviceMethodResults: ServiceMethodResults = {
79
- status: HttpStatusCode.OK,
80
- error: false,
81
- info: {
82
- data: email_send_results
346
+ const client = new RabbitMQClient({
347
+ connection_url: process.env.RABBITMQ_URL!,
348
+ delayStart: 1500,
349
+ prefetch: 25,
350
+ retryAttempts: 3,
351
+ retryDelay: 2000,
352
+ rpcRequestTimeoutMs: 30000,
353
+ metrics: true,
354
+ autoAckUnhandledMessageTypes: true,
355
+ logger: {
356
+ info: (...args) => console.info('[rmq]', ...args),
357
+ warn: (...args) => console.warn('[rmq]', ...args),
358
+ error: (...args) => console.error('[rmq]', ...args)
359
+ },
360
+ queues: [
361
+ {
362
+ name: 'emails',
363
+ handleMessageTypes: ['SEND_EMAIL', 'EMAIL_SENT'],
364
+ options: { durable: true }
365
+ }
366
+ ],
367
+ exchanges: [
368
+ {
369
+ name: 'app.events',
370
+ type: 'fanout',
371
+ options: { durable: true }
83
372
  }
84
- };
85
-
86
- event.ack(event.message);
87
- return rmqClient.publishEvent({
88
- exchange: MicroservicesExchanges.EMAIL_EVENTS,
89
- data: serviceMethodResults,
90
- publishOptions: {
91
- type: EmailsQueueEventTypes.SENT_EMAIL,
92
- contentType: ContentTypes.JSON,
93
- correlationId: event.message.properties.correlationId,
94
- replyTo: event.message.properties.replyTo,
373
+ ],
374
+ bindings: [
375
+ {
376
+ queue: 'emails',
377
+ exchange: 'app.events',
378
+ routingKey: '#'
95
379
  }
96
- });
97
- }
380
+ ]
381
+ });
382
+
383
+ const emailsQueue = client.onQueue('emails');
384
+
385
+ emailsQueue.handle('SEND_EMAIL').subscribe({
386
+ next: async (event: RmqEventMessage) => {
387
+ try {
388
+ const payload = event.data as { to: string; subject: string; html: string };
389
+ console.log('Sending email', payload);
390
+ event.ack();
391
+ client.publishEvent({
392
+ exchange: 'app.events',
393
+ routingKey: 'email.sent',
394
+ data: { ok: true, to: payload.to },
395
+ publishOptions: {
396
+ type: 'EMAIL_SENT',
397
+ contentType: ContentTypes.JSON,
398
+ persistent: true
399
+ }
400
+ });
401
+ } catch (error) {
402
+ client.deadLetter(event.message, 'email send failed', 'emails.dlq');
403
+ }
404
+ }
405
+ });
406
+
407
+ process.on('SIGINT', async () => {
408
+ await client.close();
409
+ process.exit(0);
410
+ });
411
+ ```
412
+
413
+ ## Design goals and trade-offs
414
+
415
+ This package intentionally favors simplicity over abstraction. It does not hide RabbitMQ details completely, and it does not force a specific application-level architecture. Instead, it gives you:
416
+
417
+ - a direct client
418
+ - RxJS streams
419
+ - explicit message acknowledgement
420
+ - configurable production defaults
421
+ - small extension points for serializers, retries, and metrics
422
+
423
+ That makes it easy to reason about and safe to use in microservice environments without introducing lots of hidden behavior.
424
+
425
+ ## Stability guidance
426
+
427
+ The same library should remain stable if you follow a few rules:
428
+
429
+ - keep message types explicit
430
+ - prefer `ack()` only after successful processing
431
+ - use `nack()` and `retryMessage()` only when you own the retry strategy
432
+ - use `logger` and `metrics` as opt-in production controls
433
+ - do not rely on implicit routing behavior for critical workflows
434
+
435
+ ## Contributing
436
+
437
+ This project is intentionally small. Improvements are most welcome when they:
438
+
439
+ - reduce operational risk
440
+ - improve RxJS ergonomics
441
+ - maintain a simple public API
442
+ - do not quietly introduce opinionated infrastructure behavior
443
+
444
+ ## License
445
+
446
+ ISC
447
+
448
+ ## Support
98
449
 
99
- ```
450
+ This package assumes you already understand RabbitMQ semantics and the application-level contract around your queues, exchanges, and routing keys.
@@ -1,3 +1,4 @@
1
+ /// <reference types="node" />
1
2
  import { Connection, Channel, Options, ConsumeMessage } from "amqplib";
2
3
  import { Observable, Subscription } from "rxjs";
3
4
  import { RabbitMqInitConfig, RmqEventHandler, RmqEventMessage, RmqPublishEventParams, RmqSendMessageParams } from "./types";
@@ -7,12 +8,15 @@ export type RmgOnEventHandler = (event: RmqEventMessage, rmqClient?: RabbitMQCli
7
8
  */
8
9
  export declare class RabbitMQClient {
9
10
  private clientInitConfig;
11
+ private logger;
10
12
  private connection;
11
13
  private channel;
12
14
  private isReady;
13
15
  private isReadyStream;
14
16
  private connectionErrorStream;
15
17
  private connectionCloseStream;
18
+ private reconnectTimeout;
19
+ private reconnectAttempts;
16
20
  private messagesStream;
17
21
  private messagesStreamsByQueue;
18
22
  private queues;
@@ -20,14 +24,34 @@ export declare class RabbitMQClient {
20
24
  private bindings;
21
25
  private DEFAULT_LISTENER_TYPE;
22
26
  private queueListeners;
27
+ private registeredQueueConsumers;
28
+ private metricsEnabled;
29
+ private metrics;
23
30
  private queueToEventHandleMapping;
24
31
  private queueToEventCallbackMapping;
32
+ private log;
25
33
  get onReady(): Observable<boolean>;
26
34
  get onConnectionError(): Observable<any>;
27
35
  get onConnectionClose(): Observable<any>;
28
36
  get onMessage(): Observable<RmqEventMessage>;
29
37
  constructor(clientInitConfig: RabbitMqInitConfig);
30
- init(): Promise<void> | undefined;
38
+ static registerSerializer(contentType: string, serializer: {
39
+ serialize: (value: unknown) => Buffer;
40
+ deserialize: (value: Buffer, encoding?: BufferEncoding) => unknown;
41
+ }): import("./types").RabbitMqSerializer;
42
+ getMetrics(): {
43
+ messagesReceived: number;
44
+ messagesPublished: number;
45
+ messagesAcked: number;
46
+ messagesNacked: number;
47
+ messagesRetried: number;
48
+ rpcRequests: number;
49
+ rpcResponses: number;
50
+ reconnects: number;
51
+ };
52
+ private resubscribeToRegisteredQueues;
53
+ private scheduleReconnect;
54
+ init(): Promise<void>;
31
55
  getConnection(): Connection;
32
56
  getChannel(): Channel;
33
57
  private getQueueListener;
@@ -40,12 +64,20 @@ export declare class RabbitMQClient {
40
64
  };
41
65
  forQueue(queue: string, options?: Options.Consume): Observable<RmqEventMessage>;
42
66
  ack(message: ConsumeMessage): void;
67
+ nack(message: ConsumeMessage, requeue?: boolean): void;
68
+ retryMessage(message: ConsumeMessage, options?: {
69
+ delayMs?: number;
70
+ requeue?: boolean;
71
+ queue?: string;
72
+ }): void;
73
+ deadLetter(message: ConsumeMessage, reason: string, queue?: string): void;
74
+ close(): Promise<void>;
43
75
  sendMessage(options: RmqSendMessageParams): void;
44
76
  private getRpcMethods;
45
77
  sendRequest<T = any>(options: {
46
78
  queue: string;
47
79
  data: any;
48
80
  publishOptions: Options.Publish;
49
- }): Promise<RmqEventMessage<T>>;
81
+ }, autoAckOnReceiveReply?: boolean, timeoutMs?: number): Promise<RmqEventMessage<T>>;
50
82
  publishEvent(options: RmqPublishEventParams): void;
51
83
  }