rxjs-rabbitmq 1.1.0 → 2.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 CHANGED
@@ -1,4 +1,4 @@
1
- # RxJS Rabbit MQ Client
1
+ # RxJS RabbitMQ Client
2
2
 
3
3
 
4
4
 
@@ -0,0 +1,79 @@
1
+ export declare enum ContentTypes {
2
+ JSON = "application/json",
3
+ TEXT = "text/plain",
4
+ STREAM = "application/octet-stream"
5
+ }
6
+ export declare enum MimeTypes {
7
+ AAC = "audio/aac",
8
+ ABW = "application/x-abiword",
9
+ ARC = "application/x-freearc",
10
+ AVI = "video/x-msvideo",
11
+ AZW = "application/vnd.amazon.ebook",
12
+ BIN = "application/octet-stream",
13
+ BMP = "image/bmp",
14
+ BZ = "application/x-bzip",
15
+ BZ2 = "application/x-bzip2",
16
+ CSH = "application/x-csh",
17
+ CSS = "text/css",
18
+ CSV = "text/csv",
19
+ DOC = "application/msword",
20
+ DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
21
+ EOT = "application/vnd.ms-fontobject",
22
+ EPUB = "application/epub+zip",
23
+ GZ = "application/gzip",
24
+ GIF = "image/gif",
25
+ HTM = "text/html",
26
+ HTML = "text/html",
27
+ ICO = "image/vnd.microsoft.icon",
28
+ ICS = "text/calendar",
29
+ JAR = "application/java-archive",
30
+ JPEG = "jpg",
31
+ JS = "text/javascript",
32
+ JSON = "application/json",
33
+ JSONLD = "application/ld+json",
34
+ MID = ".midi",
35
+ MJS = "text/javascript",
36
+ MP3 = "audio/mpeg",
37
+ MPEG = "video/mpeg",
38
+ MPKG = "application/vnd.apple.installer+xml",
39
+ ODP = "application/vnd.oasis.opendocument.presentation",
40
+ ODS = "application/vnd.oasis.opendocument.spreadsheet",
41
+ ODT = "application/vnd.oasis.opendocument.text",
42
+ OGA = "audio/ogg",
43
+ OGV = "video/ogg",
44
+ OGX = "application/ogg",
45
+ OPUS = "audio/opus",
46
+ OTF = "font/otf",
47
+ PNG = "image/png",
48
+ PDF = "application/pdf",
49
+ PHP = "application/php",
50
+ PPT = "application/vnd.ms-powerpoint",
51
+ PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation",
52
+ RAR = "application/vnd.rar",
53
+ RTF = "application/rtf",
54
+ SH = "application/x-sh",
55
+ SVG = "image/svg+xml",
56
+ SWF = "application/x-shockwave-flash",
57
+ TAR = "application/x-tar",
58
+ TIF = "image/tiff",
59
+ TIFF = "image/tiff",
60
+ TS = "video/mp2t",
61
+ TTF = "font/ttf",
62
+ TXT = "text/plain",
63
+ VSD = "application/vnd.visio",
64
+ WAV = "audio/wav",
65
+ WEBA = "audio/webm",
66
+ WEBM = "video/webm",
67
+ WEBP = "image/webp",
68
+ WOFF = "font/woff",
69
+ WOFF2 = "font/woff2",
70
+ XHTML = "application/xhtml+xml",
71
+ XLS = "application/vnd.ms-excel",
72
+ XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
73
+ XML = "XML",
74
+ XUL = "application/vnd.mozilla.xul+xml",
75
+ ZIP = "application/zip",
76
+ VIDEO_3GP = "video/3gpp",
77
+ VIDEO_3G2 = "video/3gpp2",
78
+ COMPRESS_7Z = "application/x-7z-compressed"
79
+ }
package/dist/enums.js ADDED
@@ -0,0 +1,82 @@
1
+ export var ContentTypes;
2
+ (function (ContentTypes) {
3
+ ContentTypes["JSON"] = "application/json";
4
+ ContentTypes["TEXT"] = "text/plain";
5
+ ContentTypes["STREAM"] = "application/octet-stream";
6
+ })(ContentTypes || (ContentTypes = {}));
7
+ export var MimeTypes;
8
+ (function (MimeTypes) {
9
+ MimeTypes["AAC"] = "audio/aac";
10
+ MimeTypes["ABW"] = "application/x-abiword";
11
+ MimeTypes["ARC"] = "application/x-freearc";
12
+ MimeTypes["AVI"] = "video/x-msvideo";
13
+ MimeTypes["AZW"] = "application/vnd.amazon.ebook";
14
+ MimeTypes["BIN"] = "application/octet-stream";
15
+ MimeTypes["BMP"] = "image/bmp";
16
+ MimeTypes["BZ"] = "application/x-bzip";
17
+ MimeTypes["BZ2"] = "application/x-bzip2";
18
+ MimeTypes["CSH"] = "application/x-csh";
19
+ MimeTypes["CSS"] = "text/css";
20
+ MimeTypes["CSV"] = "text/csv";
21
+ MimeTypes["DOC"] = "application/msword";
22
+ MimeTypes["DOCX"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
23
+ MimeTypes["EOT"] = "application/vnd.ms-fontobject";
24
+ MimeTypes["EPUB"] = "application/epub+zip";
25
+ MimeTypes["GZ"] = "application/gzip";
26
+ MimeTypes["GIF"] = "image/gif";
27
+ MimeTypes["HTM"] = "text/html";
28
+ MimeTypes["HTML"] = "text/html";
29
+ MimeTypes["ICO"] = "image/vnd.microsoft.icon";
30
+ MimeTypes["ICS"] = "text/calendar";
31
+ MimeTypes["JAR"] = "application/java-archive";
32
+ MimeTypes["JPEG"] = "jpg";
33
+ MimeTypes["JS"] = "text/javascript";
34
+ MimeTypes["JSON"] = "application/json";
35
+ MimeTypes["JSONLD"] = "application/ld+json";
36
+ MimeTypes["MID"] = ".midi";
37
+ MimeTypes["MJS"] = "text/javascript";
38
+ MimeTypes["MP3"] = "audio/mpeg";
39
+ MimeTypes["MPEG"] = "video/mpeg";
40
+ MimeTypes["MPKG"] = "application/vnd.apple.installer+xml";
41
+ MimeTypes["ODP"] = "application/vnd.oasis.opendocument.presentation";
42
+ MimeTypes["ODS"] = "application/vnd.oasis.opendocument.spreadsheet";
43
+ MimeTypes["ODT"] = "application/vnd.oasis.opendocument.text";
44
+ MimeTypes["OGA"] = "audio/ogg";
45
+ MimeTypes["OGV"] = "video/ogg";
46
+ MimeTypes["OGX"] = "application/ogg";
47
+ MimeTypes["OPUS"] = "audio/opus";
48
+ MimeTypes["OTF"] = "font/otf";
49
+ MimeTypes["PNG"] = "image/png";
50
+ MimeTypes["PDF"] = "application/pdf";
51
+ MimeTypes["PHP"] = "application/php";
52
+ MimeTypes["PPT"] = "application/vnd.ms-powerpoint";
53
+ MimeTypes["PPTX"] = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
54
+ MimeTypes["RAR"] = "application/vnd.rar";
55
+ MimeTypes["RTF"] = "application/rtf";
56
+ MimeTypes["SH"] = "application/x-sh";
57
+ MimeTypes["SVG"] = "image/svg+xml";
58
+ MimeTypes["SWF"] = "application/x-shockwave-flash";
59
+ MimeTypes["TAR"] = "application/x-tar";
60
+ MimeTypes["TIF"] = "image/tiff";
61
+ MimeTypes["TIFF"] = "image/tiff";
62
+ MimeTypes["TS"] = "video/mp2t";
63
+ MimeTypes["TTF"] = "font/ttf";
64
+ MimeTypes["TXT"] = "text/plain";
65
+ MimeTypes["VSD"] = "application/vnd.visio";
66
+ MimeTypes["WAV"] = "audio/wav";
67
+ MimeTypes["WEBA"] = "audio/webm";
68
+ MimeTypes["WEBM"] = "video/webm";
69
+ MimeTypes["WEBP"] = "image/webp";
70
+ MimeTypes["WOFF"] = "font/woff";
71
+ MimeTypes["WOFF2"] = "font/woff2";
72
+ MimeTypes["XHTML"] = "application/xhtml+xml";
73
+ MimeTypes["XLS"] = "application/vnd.ms-excel";
74
+ MimeTypes["XLSX"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
75
+ MimeTypes["XML"] = "XML";
76
+ MimeTypes["XUL"] = "application/vnd.mozilla.xul+xml";
77
+ MimeTypes["ZIP"] = "application/zip";
78
+ MimeTypes["VIDEO_3GP"] = "video/3gpp";
79
+ MimeTypes["VIDEO_3G2"] = "video/3gpp2";
80
+ MimeTypes["COMPRESS_7Z"] = "application/x-7z-compressed";
81
+ })(MimeTypes || (MimeTypes = {}));
82
+ //# sourceMappingURL=enums.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enums.js","sourceRoot":"","sources":["../src/enums.ts"],"names":[],"mappings":"AAAA,MAAM,CAAN,IAAY,YAIX;AAJD,WAAY,YAAY;IACtB,yCAAyB,CAAA;IACzB,mCAAmB,CAAA;IACnB,mDAAmC,CAAA;AACrC,CA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AAA;IAClB,0CAA6B,CAAA;IAC7B,8BAAiB,CAAA;IACjB,gCAAmB,CAAA;IACnB,gCAAmB,CAAA;IACnB,gCAAmB,CAAA;IACnB,+BAAkB,CAAA;IAClB,iCAAoB,CAAA;IACpB,4CAA+B,CAAA;IAC/B,6CAAgC,CAAA;IAChC,uFAA0E,CAAA;IAC1E,wBAAW,CAAA;IACX,oDAAuC,CAAA;IACvC,oCAAuB,CAAA;IACvB,qCAAwB,CAAA;IACxB,sCAAyB,CAAA;IACzB,wDAA2C,CAAA;AAC7C,CAAC,EAzEW,SAAS,KAAT,SAAS,QAyEpB"}
@@ -0,0 +1,4 @@
1
+ export * from './enums';
2
+ export * from './types';
3
+ export * from './utils';
4
+ export * from './rabbitmq-client.helper';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from './enums';
2
+ export * from './types';
3
+ export * from './utils';
4
+ export * from './rabbitmq-client.helper';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,cAAc,0BAA0B,CAAC"}
@@ -0,0 +1,49 @@
1
+ /// <reference types="node" />
2
+ import { Connection, Channel, Options, ConsumeMessage } from "amqplib";
3
+ import { Observable, Subscription } from "rxjs";
4
+ import { RabbitMqInitConfig, RmqEventMessage, RmqPublishEventParams, RmqSendMessageParams } from "./types";
5
+ export type RmgOnEventHandler = (event: RmqEventMessage, rmqClient?: RabbitMQClient) => void;
6
+ /**
7
+ Rabbit MQ - RxJS Powered
8
+ */
9
+ export declare class RabbitMQClient {
10
+ private clientInitConfig;
11
+ private connection;
12
+ private channel;
13
+ private isReady;
14
+ private isReadyStream;
15
+ private connectionErrorStream;
16
+ private connectionCloseStream;
17
+ private messagesStream;
18
+ private queues;
19
+ private exchanges;
20
+ private bindings;
21
+ private DEFAULT_LISTENER_TYPE;
22
+ private EXCLUSIVE_QUEUE;
23
+ private queueListeners;
24
+ private queueToEventHandleMapping;
25
+ private queueToEventCallbackMapping;
26
+ get onReady(): Observable<boolean>;
27
+ get onConnectionError(): Observable<any>;
28
+ get onConnectionClose(): Observable<any>;
29
+ get onMessage(): Observable<RmqEventMessage>;
30
+ constructor(clientInitConfig: RabbitMqInitConfig);
31
+ init(clientInitConfig: RabbitMqInitConfig): Promise<void>;
32
+ getConnection(): Observable<Connection>;
33
+ getChannel(): Observable<Channel>;
34
+ private getQueueListener;
35
+ onQueue(queue: string, options?: Options.Consume): {
36
+ handle: (messageType: string) => Observable<RmqEventMessage>;
37
+ handleDefault: () => Observable<RmqEventMessage>;
38
+ onEvent: (messageType: string, handlerFn: RmgOnEventHandler) => Observable<Subscription>;
39
+ };
40
+ ack(message: ConsumeMessage): void;
41
+ sendMessage(options: RmqSendMessageParams): Promise<unknown>;
42
+ sendRequest<T = any>(options: {
43
+ queue: string;
44
+ data: any;
45
+ publishOptions: Options.Publish;
46
+ }): Promise<RmqEventMessage<T>>;
47
+ publishEvent(options: RmqPublishEventParams): void;
48
+ listen(): NodeJS.Timeout;
49
+ }
@@ -0,0 +1,388 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { v1 as uuidv1 } from 'uuid';
11
+ import { connect } from "amqplib";
12
+ import { BehaviorSubject, filter, firstValueFrom, map, mergeMap, ReplaySubject, Subject, take, tap, } from "rxjs";
13
+ import { mapify, SERIALIZERS, uniqueValue, wait } from "./utils";
14
+ import { ContentTypes } from "./enums";
15
+ /**
16
+ Rabbit MQ - RxJS Powered
17
+ */
18
+ export class RabbitMQClient {
19
+ get onReady() {
20
+ return this.isReadyStream.asObservable().pipe(filter((state) => !!state), take(1));
21
+ }
22
+ get onConnectionError() {
23
+ return this.connectionErrorStream.asObservable();
24
+ }
25
+ get onConnectionClose() {
26
+ return this.connectionCloseStream.asObservable();
27
+ }
28
+ get onMessage() {
29
+ return this.messagesStream.asObservable();
30
+ }
31
+ constructor(clientInitConfig) {
32
+ this.isReady = false;
33
+ this.isReadyStream = new BehaviorSubject(this.isReady);
34
+ this.connectionErrorStream = new Subject();
35
+ this.connectionCloseStream = new Subject();
36
+ this.messagesStream = new Subject();
37
+ this.queues = {};
38
+ this.exchanges = {};
39
+ this.bindings = [];
40
+ this.DEFAULT_LISTENER_TYPE = '__default';
41
+ this.EXCLUSIVE_QUEUE = uuidv1();
42
+ this.queueListeners = {};
43
+ this.queueToEventHandleMapping = {};
44
+ this.queueToEventCallbackMapping = {};
45
+ this.init(clientInitConfig);
46
+ }
47
+ init(clientInitConfig) {
48
+ this.clientInitConfig = clientInitConfig;
49
+ const { delayStart, connection_url, prefetch, queues, exchanges, bindings, pre_init_promises, post_init_promises } = clientInitConfig;
50
+ let retryAttempts = clientInitConfig.retryAttempts || 0;
51
+ const retryDelay = clientInitConfig.retryDelay || 0;
52
+ const init = () => {
53
+ console.log(`Attempting connection to Rabbit MQ...`);
54
+ return connect(connection_url)
55
+ .then((connection) => {
56
+ this.connection = connection;
57
+ console.log(`connected to message server`);
58
+ return this.connection.createChannel();
59
+ })
60
+ .then((channel) => {
61
+ this.channel = channel;
62
+ if (prefetch) {
63
+ this.channel.prefetch(prefetch || 1);
64
+ }
65
+ console.log(`channel created on message server`);
66
+ })
67
+ .then(() => {
68
+ // create an exclusive queue for this channel connection
69
+ console.log(`Creating exclusive queue ${this.EXCLUSIVE_QUEUE}`);
70
+ return this.channel.assertQueue(this.EXCLUSIVE_QUEUE, { exclusive: true, durable: false }).then((response) => {
71
+ console.log(`Created exclusive queue ${this.EXCLUSIVE_QUEUE}`);
72
+ });
73
+ })
74
+ .then(() => {
75
+ const promises = [];
76
+ // by default, create an observable stream on the queue for unidentified/null routing keys
77
+ for (const queueConfig of queues) {
78
+ this.queueToEventHandleMapping[queueConfig.name] = {};
79
+ this.queueToEventCallbackMapping[queueConfig.name] = {};
80
+ const queueListenersMap = this.queueToEventHandleMapping[queueConfig.name];
81
+ const queueCallbacksMap = this.queueToEventCallbackMapping[queueConfig.name];
82
+ queueListenersMap[this.DEFAULT_LISTENER_TYPE] = new ReplaySubject();
83
+ for (const messageType of queueConfig.handleMessageTypes) {
84
+ const isStringList = typeof messageType === 'string';
85
+ if (isStringList) {
86
+ queueListenersMap[messageType] = new ReplaySubject();
87
+ }
88
+ else {
89
+ queueCallbacksMap[messageType.messageName] = messageType.callbackHandler;
90
+ }
91
+ }
92
+ promises.push(this.channel.assertQueue(queueConfig.name, queueConfig.options));
93
+ }
94
+ return Promise.all(promises).then((values) => {
95
+ this.queues = mapify(values, 'queue');
96
+ console.log(`queues created on channel`);
97
+ });
98
+ })
99
+ .then(() => {
100
+ const promises = exchanges.map((config) => this.channel.assertExchange(config.name, config.type, config.options));
101
+ return Promise.all(promises).then(values => {
102
+ this.exchanges = mapify(values, 'exchange');
103
+ console.log(`exchanges created on channel`);
104
+ });
105
+ })
106
+ .then(() => {
107
+ const promises = bindings.map((config) => this.channel.bindQueue(config.queue, config.exchange, config.routingKey));
108
+ // bind the exclusive queue to all the exchanges
109
+ // const exclusiveBindings = bindings.map((config) => this.channel.bindQueue(this.EXCLUSIVE_QUEUE, config.exchange, config.routingKey));
110
+ return Promise.all(promises).then(values => {
111
+ console.log(`bindings created on channel`);
112
+ });
113
+ })
114
+ .then(() => {
115
+ console.log(`Client initialization complete; waiting for messages/events...\n`);
116
+ // initialization complete; listen for connection issues to retry again
117
+ retryAttempts = clientInitConfig.retryAttempts;
118
+ this.connection.on("error", (err) => {
119
+ this.connectionErrorStream.next(err);
120
+ });
121
+ this.connection.on("close", (err) => {
122
+ this.connectionErrorStream.next(err);
123
+ });
124
+ this.isReady = true;
125
+ this.isReadyStream.next(true);
126
+ })
127
+ .catch((error) => {
128
+ console.log(`connection error, retryAttempts: ${retryAttempts}`, error);
129
+ if (retryAttempts === 0) {
130
+ console.log(`all retry attemptys exhaused; exiting...`);
131
+ throw error;
132
+ }
133
+ retryAttempts = retryAttempts - 1;
134
+ return wait(retryDelay).then(init);
135
+ });
136
+ };
137
+ return wait(delayStart || 0)
138
+ .then(() => {
139
+ console.log(`Running pre init promises...`);
140
+ return Promise.all((pre_init_promises === null || pre_init_promises === void 0 ? void 0 : pre_init_promises.map(p => p instanceof Promise ? p : p())) || []).then(() => {
141
+ console.log(`Done running pre init promises.\n`);
142
+ });
143
+ })
144
+ .then(init)
145
+ .then(() => {
146
+ console.log(`Running post init promises...`);
147
+ return Promise.all((post_init_promises === null || post_init_promises === void 0 ? void 0 : post_init_promises.map(p => p instanceof Promise ? p : p())) || []).then(() => {
148
+ console.log(`Done running post init promises. `);
149
+ });
150
+ });
151
+ }
152
+ getConnection() {
153
+ return this.onReady.pipe(map(() => this.connection));
154
+ }
155
+ getChannel() {
156
+ return this.onReady.pipe(map(() => this.channel));
157
+ }
158
+ getQueueListener(queue, options) {
159
+ return () => {
160
+ const handleCallback = (message) => {
161
+ if (!message) {
162
+ throw new Error('Consumer cancelled by server');
163
+ }
164
+ console.log(`received queue message`, message);
165
+ // see if a listener was created for the routing key
166
+ const messageType = message.properties.type;
167
+ const useContentType = message.properties.contentType;
168
+ const useData = SERIALIZERS[useContentType] ? SERIALIZERS[useContentType].deserialize(message.content) : message.content;
169
+ const messageObj = {
170
+ data: useData,
171
+ message,
172
+ ack: () => {
173
+ this.ack(message);
174
+ },
175
+ sendMessage: this.sendMessage.bind(this),
176
+ sendRequest: this.sendRequest.bind(this),
177
+ publishEvent: this.publishEvent.bind(this),
178
+ };
179
+ // send message to stream
180
+ this.messagesStream.next(messageObj);
181
+ // console.log(`Message on queue ${queue}:`, messageObj);
182
+ if (!messageType) {
183
+ // no type key found, push to default stream
184
+ console.log(`No message type found; pushing to default handler on queue ${queue}`);
185
+ this.queueToEventHandleMapping[queue][this.DEFAULT_LISTENER_TYPE].next(messageObj);
186
+ return;
187
+ }
188
+ if (this.queueToEventHandleMapping[queue][messageType]) {
189
+ // there is a registered listener for the type, push to that stream
190
+ console.log(`message type handler found; pushing to ${messageType} handler on queue ${queue}`);
191
+ this.queueToEventHandleMapping[queue][messageType].next(messageObj);
192
+ }
193
+ else if (this.queueToEventCallbackMapping[queue][messageType]) {
194
+ // there is a registered listener for the type, push to that stream
195
+ console.log(`message type callback found; pushing to ${messageType} callback on queue ${queue}`);
196
+ const callbackHandler = this.queueToEventCallbackMapping[queue][messageType];
197
+ callbackHandler(messageObj);
198
+ }
199
+ else {
200
+ // no registered listener
201
+ if (this.clientInitConfig.autoAckUnhandledMessageTypes) {
202
+ console.log(`No handler found for message type ${messageType} on queue ${queue}; auto acknowledging.`);
203
+ this.ack(message);
204
+ return;
205
+ }
206
+ else if (this.clientInitConfig.pushUnhandledMessageTypesToDefaultHandler) {
207
+ console.log(`No handler found for message type ${messageType} on queue ${queue}; pushing to ${this.DEFAULT_LISTENER_TYPE} handler.`);
208
+ this.queueToEventHandleMapping[queue][this.DEFAULT_LISTENER_TYPE].next(messageObj);
209
+ return;
210
+ }
211
+ else {
212
+ throw new Error(`Message received with unregistered message type handler/callback. Please add message type "${messageType}" in the list of message types for the queue config in the constructor.`);
213
+ }
214
+ }
215
+ };
216
+ const consumerTag = Date.now().toString();
217
+ this.channel.consume(queue, handleCallback, Object.assign(Object.assign({}, (options || {})), { consumerTag: (options === null || options === void 0 ? void 0 : options.consumerTag) || consumerTag }));
218
+ };
219
+ }
220
+ onQueue(queue, options) {
221
+ // listen for messages on the queue
222
+ if (!this.queueListeners[queue]) {
223
+ console.log(`Registering messages/events listener for queue ${queue}:`);
224
+ const startQueueListener = this.getQueueListener(queue, options);
225
+ this.queueListeners[queue] = this.onReady.pipe(tap((readyState) => {
226
+ startQueueListener();
227
+ }))
228
+ .subscribe({
229
+ next: (readyState) => {
230
+ console.log(`Registered: Now listening to messages/events on queue ${queue}...`);
231
+ }
232
+ });
233
+ }
234
+ const handle = (messageType) => {
235
+ return this.onReady.pipe(mergeMap((ready, index) => {
236
+ if (!this.queueToEventHandleMapping[queue][messageType]) {
237
+ throw new Error(`The provided routing key was not provided during initialization. Please add routing key "${messageType}" in the list of routing keys for the queue config in the constructor.`);
238
+ }
239
+ return this.queueToEventHandleMapping[queue][messageType].asObservable();
240
+ }));
241
+ };
242
+ const handleDefault = () => {
243
+ return this.onReady.pipe(mergeMap((ready, index) => this.queueToEventHandleMapping[queue][this.DEFAULT_LISTENER_TYPE].asObservable()));
244
+ };
245
+ const onEvent = (messageType, handlerFn) => {
246
+ return this.onReady.pipe(map((ready) => {
247
+ if (!this.queueToEventCallbackMapping[queue][messageType]) {
248
+ throw new Error(`The provided routing key was not provided during initialization. Please add routing key "${messageType}" in the list of routing keys for the queue config in the constructor.`);
249
+ }
250
+ return this.queueToEventHandleMapping[queue][messageType].asObservable().subscribe({
251
+ next: (event) => {
252
+ handlerFn(event, this);
253
+ }
254
+ });
255
+ }));
256
+ };
257
+ return {
258
+ handle,
259
+ handleDefault,
260
+ onEvent
261
+ };
262
+ }
263
+ ack(message) {
264
+ this.channel.ack(message);
265
+ console.log(`Acknoledged rmq message.`);
266
+ }
267
+ sendMessage(options) {
268
+ return new Promise((resolve, reject) => {
269
+ const send = () => {
270
+ const { data, publishOptions, queue } = options;
271
+ const useContentType = publishOptions.contentType || ContentTypes.TEXT;
272
+ const useData = SERIALIZERS[useContentType] ? SERIALIZERS[useContentType].serialize(data) : data;
273
+ this.channel.sendToQueue(queue, useData, Object.assign(Object.assign({}, publishOptions), { appId: publishOptions.appId }));
274
+ resolve(undefined);
275
+ };
276
+ if (!this.isReady) {
277
+ console.log(`wait until ready to send message...`);
278
+ firstValueFrom(this.onReady).then((readyState) => {
279
+ console.log(`now ready to send message`, { readyState });
280
+ send();
281
+ });
282
+ }
283
+ else {
284
+ console.log(`is ready to send message`);
285
+ send();
286
+ }
287
+ });
288
+ }
289
+ sendRequest(options) {
290
+ console.log(`sendRequest:`, options);
291
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
292
+ const start_time = Date.now();
293
+ const consumerTag = uniqueValue();
294
+ const correlationId = options.publishOptions.correlationId || uniqueValue();
295
+ const temporaryRpcQueue = uuidv1();
296
+ const newQueue = yield this.channel.assertQueue(temporaryRpcQueue, { exclusive: true, durable: false, autoDelete: true }).then((response) => {
297
+ console.log(`Created temp queue ${temporaryRpcQueue} for client.`);
298
+ return response;
299
+ });
300
+ const send = () => {
301
+ const { data, publishOptions, queue } = options;
302
+ const useContentType = publishOptions.contentType || ContentTypes.TEXT;
303
+ const useData = SERIALIZERS[useContentType] ? SERIALIZERS[useContentType].serialize(data) : data;
304
+ this.channel.sendToQueue(queue, useData, Object.assign(Object.assign({}, publishOptions), { correlationId, replyTo: temporaryRpcQueue, appId: publishOptions.appId }));
305
+ };
306
+ const watch = () => {
307
+ console.log(`request/rpc sent; awaiting response...`, { correlationId, consumerTag });
308
+ const replyHandler = (message) => {
309
+ console.log(`\nReceived reply.\n`, { message });
310
+ const correlationIdMatch = message.properties.correlationId == correlationId;
311
+ const isReplyToRequest = !!message && correlationIdMatch;
312
+ console.log({ isReplyToRequest, consumerTag, correlationIdMatch, requestCorrelationId: correlationId, responseCorrelationId: message.properties.correlationId });
313
+ if (isReplyToRequest) {
314
+ this.ack(message);
315
+ const useContentType = message.properties.contentType;
316
+ const useData = SERIALIZERS[useContentType] ? SERIALIZERS[useContentType].deserialize(message.content) : message.content;
317
+ const messageObj = {
318
+ data: useData,
319
+ message: message,
320
+ ack: () => {
321
+ this.ack(message);
322
+ },
323
+ sendMessage: this.sendMessage.bind(this),
324
+ sendRequest: this.sendRequest.bind(this),
325
+ publishEvent: this.publishEvent.bind(this),
326
+ };
327
+ const end_time = Date.now();
328
+ const total_time = (end_time - start_time) / 1000;
329
+ const time_in_seconds = total_time.toFixed();
330
+ console.log(`received response from request/rpc:`, { start_time, end_time, total_time, time_in_seconds, messageObj, options });
331
+ resolve(messageObj);
332
+ this.channel.cancel(consumerTag).then(() => {
333
+ console.log(`removed consumer via consumerTag`);
334
+ });
335
+ }
336
+ };
337
+ this.channel.consume(temporaryRpcQueue, replyHandler, { consumerTag });
338
+ };
339
+ if (!this.isReady) {
340
+ console.log(`waiting until ready to send request`);
341
+ firstValueFrom(this.onReady).then((readyState) => {
342
+ console.log(`now ready to publish event`, { readyState });
343
+ watch(); // first listen on the reply queue
344
+ send(); // then send the rpc/rmq message
345
+ });
346
+ }
347
+ else {
348
+ console.log(`is ready to send request`);
349
+ watch();
350
+ send();
351
+ }
352
+ }));
353
+ }
354
+ publishEvent(options) {
355
+ const publish = () => {
356
+ const { data, routingKey, publishOptions, exchange } = options;
357
+ const useContentType = publishOptions.contentType || ContentTypes.TEXT;
358
+ const useData = SERIALIZERS[useContentType] ? SERIALIZERS[useContentType].serialize(data) : data;
359
+ this.channel.publish(exchange, routingKey, useData, Object.assign(Object.assign({}, publishOptions), { appId: publishOptions.appId }));
360
+ if (publishOptions.replyTo && !this.clientInitConfig.dontSendToReplyQueueOnPublish) {
361
+ console.log(`sending copy to reply to queue ${publishOptions.replyTo}...`);
362
+ this.channel.sendToQueue(publishOptions.replyTo, useData, publishOptions);
363
+ }
364
+ };
365
+ if (!this.isReady) {
366
+ console.log(`wait until ready to publish event`);
367
+ this.onReady.subscribe({
368
+ next: (readyState) => {
369
+ console.log(`now ready to publish event`, { readyState });
370
+ readyState && publish();
371
+ }
372
+ });
373
+ }
374
+ else {
375
+ console.log(`is ready to publish event`);
376
+ publish();
377
+ }
378
+ }
379
+ listen() {
380
+ // last resort to keeping the node.js process running
381
+ const listenerCallback = () => {
382
+ console.log(`--- listening... ---`);
383
+ };
384
+ const interval = setInterval(listenerCallback, 1000 * 60 * 10);
385
+ return interval;
386
+ }
387
+ }
388
+ //# sourceMappingURL=rabbitmq-client.helper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rabbitmq-client.helper.js","sourceRoot":"","sources":["../src/rabbitmq-client.helper.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,EAIL,OAAO,EAGR,MAAM,SAAS,CAAC;AAEjB,OAAO,EACL,eAAe,EACf,MAAM,EACN,cAAc,EACd,GAAG,EACH,QAAQ,EAER,aAAa,EACb,OAAO,EAEP,IAAI,EACJ,GAAG,GACJ,MAAM,MAAM,CAAC;AAEd,OAAO,EACL,MAAM,EACN,WAAW,EACX,WAAW,EACX,IAAI,EACL,MAAM,SAAS,CAAC;AAajB,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAOvC;;EAEE;AACF,MAAM,OAAO,cAAc;IA6BzB,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,aAAa,CAAC,YAAY,EAAE,CAAC,IAAI,CAC3C,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,EAC1B,IAAI,CAAC,CAAC,CAAC,CACR,CAAC;IACJ,CAAC;IAED,IAAI,iBAAiB;QACnB,OAAO,IAAI,CAAC,qBAAqB,CAAC,YAAY,EAAE,CAAC;IACnD,CAAC;IAED,IAAI,iBAAiB;QACnB,OAAO,IAAI,CAAC,qBAAqB,CAAC,YAAY,EAAE,CAAC;IACnD,CAAC;IAED,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,cAAc,CAAC,YAAY,EAAE,CAAC;IAC5C,CAAC;IAED,YAAY,gBAAoC;QA3CxC,YAAO,GAAY,KAAK,CAAC;QACzB,kBAAa,GAA6B,IAAI,eAAe,CAAU,IAAI,CAAC,OAAO,CAAC,CAAC;QACrF,0BA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AC;CACF"}
@@ -0,0 +1,69 @@
1
+ import { Options, ConsumeMessage, Message } from "amqplib";
2
+ export type MapType<T = any> = {
3
+ [key: string]: T;
4
+ };
5
+ export type RmqMessageTypeHandler = (event: RmqEventMessage) => Promise<void>;
6
+ export type RmqHandleMessageTypeConfig = {
7
+ messageName: string;
8
+ callbackHandler: RmqMessageTypeHandler;
9
+ };
10
+ export type RmqHandleMessageTypeConfigs = string[] | RmqHandleMessageTypeConfig[];
11
+ export interface QueueConfig {
12
+ name: string;
13
+ handleMessageTypes: RmqHandleMessageTypeConfigs;
14
+ options?: Options.AssertQueue;
15
+ }
16
+ export interface ExchangeConfig {
17
+ name: string;
18
+ type: string;
19
+ options?: Options.AssertExchange;
20
+ }
21
+ export interface QueueExchangeBindingConfig {
22
+ queue: string;
23
+ exchange: string;
24
+ routingKey: string;
25
+ }
26
+ export type RmqEventRequestResponse<T = any> = Promise<RmqEventMessage<T>>;
27
+ export type RmqSendMessageParams = {
28
+ queue: string;
29
+ data: any;
30
+ publishOptions: Options.Publish;
31
+ };
32
+ export type RmqSendRequestParams = {
33
+ queue: string;
34
+ data: any;
35
+ publishOptions: Options.Publish;
36
+ };
37
+ export type RmqPublishEventParams<T = any> = {
38
+ exchange: string;
39
+ data: T;
40
+ routingKey: string;
41
+ publishOptions: Options.Publish;
42
+ };
43
+ export type RmqEventMessage<T = any> = {
44
+ data: T;
45
+ message: ConsumeMessage;
46
+ ack: () => void;
47
+ publishEvent: (options: RmqPublishEventParams) => void;
48
+ sendMessage: (options: RmqSendMessageParams) => void;
49
+ sendRequest: <T = any>(options: RmqSendRequestParams) => Promise<RmqEventMessage<T>>;
50
+ };
51
+ export type AckFn = (message: Message) => void;
52
+ export type RabbitMqInitConfig = {
53
+ dontSendToReplyQueueOnPublish?: boolean;
54
+ autoAckUnhandledMessageTypes?: boolean;
55
+ pushUnhandledMessageTypesToDefaultHandler?: boolean;
56
+ delayStart?: number;
57
+ connection_url: string;
58
+ retryAttempts: number;
59
+ retryDelay: number;
60
+ prefetch?: number;
61
+ /**
62
+ The queues you want to consume on this client
63
+ */
64
+ queues: Array<QueueConfig>;
65
+ exchanges: Array<ExchangeConfig>;
66
+ bindings: Array<QueueExchangeBindingConfig>;
67
+ pre_init_promises?: (Promise<any> | (() => Promise<any>))[];
68
+ post_init_promises?: (Promise<any> | (() => Promise<any>))[];
69
+ };
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,19 @@
1
+ /// <reference types="node" />
2
+ import { MapType } from "./types";
3
+ export declare const SERIALIZERS: {
4
+ 'application/json': {
5
+ deserialize: (bytes: any, encoding: any) => any;
6
+ serialize: (object: any) => Buffer;
7
+ };
8
+ 'application/octet-stream': {
9
+ deserialize: (bytes: any) => any;
10
+ serialize: (bytes: any) => Buffer;
11
+ };
12
+ 'text/plain': {
13
+ deserialize: (bytes: any, encoding: any) => any;
14
+ serialize: (str: string) => Buffer;
15
+ };
16
+ };
17
+ export declare const mapify: <T>(list: T[], key: string | number) => MapType<T>;
18
+ export declare const wait: (time: any) => Promise<unknown>;
19
+ export declare function uniqueValue(): string;
package/dist/utils.js ADDED
@@ -0,0 +1,53 @@
1
+ // https://github.com/Foo-Foo-MQ/foo-foo-mq/blob/main/src/index.js
2
+ export const SERIALIZERS = {
3
+ 'application/json': {
4
+ deserialize: (bytes, encoding) => {
5
+ return JSON.parse(bytes.toString(encoding || 'utf8'));
6
+ },
7
+ serialize: (object) => {
8
+ const json = (typeof object === 'string')
9
+ ? object
10
+ : JSON.stringify(object);
11
+ return Buffer.from(json, 'utf8');
12
+ }
13
+ },
14
+ 'application/octet-stream': {
15
+ deserialize: (bytes) => {
16
+ return bytes;
17
+ },
18
+ serialize: (bytes) => {
19
+ if (Buffer.isBuffer(bytes)) {
20
+ return bytes;
21
+ }
22
+ else if (Array.isArray(bytes)) {
23
+ return Buffer.from(bytes);
24
+ }
25
+ else {
26
+ throw new Error('Cannot serialize unknown data type');
27
+ }
28
+ }
29
+ },
30
+ 'text/plain': {
31
+ deserialize: (bytes, encoding) => {
32
+ return bytes.toString(encoding || 'utf8');
33
+ },
34
+ serialize: (str) => {
35
+ return Buffer.from(str, 'utf8');
36
+ }
37
+ }
38
+ };
39
+ export const mapify = (list, key) => {
40
+ return list.reduce((map, item) => {
41
+ map[item[key]] = item;
42
+ return map;
43
+ }, {});
44
+ };
45
+ export const wait = (time) => {
46
+ return new Promise((resolve) => {
47
+ setTimeout(resolve, time);
48
+ });
49
+ };
50
+ export function uniqueValue() {
51
+ return Math.random().toString(33).substring(2) + '-' + Date.now();
52
+ }
53
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAEA,kEAAkE;AAClE,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,kBAAkB,EAAE;QAClB,WAAW,EAAE,CAAC,KAAU,EAAE,QAAa,EAAE,EAAE;YACzC,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,IAAI,MAAM,CAAC,CAAC,CAAC;QACxD,CAAC;QACD,SAAS,EAAE,CAAC,MAAW,EAAE,EAAE;YACzB,MAAM,IAAI,GAAG,CAAC,OAAO,MAAM,KAAK,QAAQ,CAAC;gBACvC,CAAC,CAAC,MAAM;gBACR,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;YAC3B,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACnC,CAAC;KACF;IACD,0BAA0B,EAAE;QAC1B,WAAW,EAAE,CAAC,KAAU,EAAE,EAAE;YAC1B,OAAO,KAAK,CAAC;QACf,CAAC;QACD,SAAS,EAAE,CAAC,KAAU,EAAE,EAAE;YACxB,IA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AACpE,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rxjs-rabbitmq",
3
- "version": "1.1.0",
3
+ "version": "2.0.0",
4
4
  "description": "RxJS powered RabbitMQ event handling",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -61,16 +61,18 @@ export class RabbitMQClient {
61
61
  private connectionErrorStream: Subject<any> = new Subject<any>();
62
62
  private connectionCloseStream: Subject<any> = new Subject<any>();
63
63
 
64
+ /*
65
+ Handle all messages from all queues on this client
66
+ */
64
67
  private messagesStream: Subject<RmqEventMessage> = new Subject<RmqEventMessage>();
68
+ private messagesStreamsByQueue: MapType<Subject<RmqEventMessage>> = {};
65
69
 
66
70
  private queues: MapType<Replies.AssertQueue> = {};
67
71
  private exchanges:MapType<Replies.AssertExchange> = {};
68
72
  private bindings: QueueExchangeBindingConfig[] = [];
69
73
 
70
74
  private DEFAULT_LISTENER_TYPE = '__default';
71
-
72
75
  private EXCLUSIVE_QUEUE: string = uuidv1();
73
-
74
76
  private queueListeners: MapType<Subscription> = {};
75
77
 
76
78
  private queueToEventHandleMapping: MapType<
@@ -100,7 +102,7 @@ export class RabbitMQClient {
100
102
  }
101
103
 
102
104
  constructor(clientInitConfig: RabbitMqInitConfig) {
103
- this.init(clientInitConfig);
105
+ !clientInitConfig.stopAutoInit && this.init(clientInitConfig);
104
106
  }
105
107
 
106
108
  init(clientInitConfig: RabbitMqInitConfig) {
@@ -120,20 +122,23 @@ export class RabbitMQClient {
120
122
  const retryDelay = clientInitConfig.retryDelay || 0;
121
123
 
122
124
  const init = () => {
125
+ // creating connection
123
126
  console.log(`Attempting connection to Rabbit MQ...`);
124
127
  return connect(connection_url)
125
128
  .then((connection) => {
126
129
  this.connection = connection;
127
- console.log(`connected to message server`);
130
+ console.log(`Connected to message server`);
128
131
  return this.connection.createChannel();
129
132
  })
133
+ // creating channel
130
134
  .then((channel) => {
131
135
  this.channel = channel;
132
136
  if (prefetch) {
133
137
  this.channel.prefetch(prefetch || 1);
134
138
  }
135
- console.log(`channel created on message server`);
139
+ console.log(`Channel created on message server`);
136
140
  })
141
+ // creating exclusive queue
137
142
  .then(() => {
138
143
  // create an exclusive queue for this channel connection
139
144
  console.log(`Creating exclusive queue ${this.EXCLUSIVE_QUEUE}`);
@@ -141,26 +146,29 @@ export class RabbitMQClient {
141
146
  console.log(`Created exclusive queue ${this.EXCLUSIVE_QUEUE}`);
142
147
  });
143
148
  })
149
+ // assert to queues
144
150
  .then(() => {
145
151
  const promises: Promise<Replies.AssertQueue>[] = [];
146
- // by default, create an observable stream on the queue for unidentified/null routing keys
152
+
147
153
  for (const queueConfig of queues) {
148
154
  this.queueToEventHandleMapping[queueConfig.name] = {};
149
155
  this.queueToEventCallbackMapping[queueConfig.name] = {};
150
-
156
+
151
157
  const queueListenersMap = this.queueToEventHandleMapping[queueConfig.name];
152
158
  const queueCallbacksMap = this.queueToEventCallbackMapping[queueConfig.name];
153
-
159
+
160
+ // by default, create an observable stream on the queue for unidentified/null routing keys
154
161
  queueListenersMap[this.DEFAULT_LISTENER_TYPE] = new ReplaySubject();
155
162
 
156
- for (const messageType of queueConfig.handleMessageTypes) {
163
+ const useHandleMessageTypes = queueConfig.handleMessageTypes || [];
164
+ for (const messageType of useHandleMessageTypes) {
157
165
  const isStringList = typeof messageType === 'string';
158
-
159
166
  if (isStringList) {
160
167
  queueListenersMap[messageType as string] = new ReplaySubject();
161
168
  }
162
169
  else {
163
- queueCallbacksMap[messageType.messageName] = messageType.callbackHandler;
170
+ const config: RmqHandleMessageTypeConfig = messageType;
171
+ queueCallbacksMap[config.messageName] = config.callbackHandler;
164
172
  }
165
173
  }
166
174
 
@@ -172,6 +180,7 @@ export class RabbitMQClient {
172
180
  console.log(`queues created on channel`);
173
181
  })
174
182
  })
183
+ // assert exchanges
175
184
  .then(() => {
176
185
  const promises = exchanges.map((config) => this.channel.assertExchange(config.name, config.type, config.options));
177
186
  return Promise.all(promises).then(values => {
@@ -179,6 +188,7 @@ export class RabbitMQClient {
179
188
  console.log(`exchanges created on channel`);
180
189
  });
181
190
  })
191
+ // apply bindings
182
192
  .then(() => {
183
193
  const promises = bindings.map((config) => this.channel.bindQueue(config.queue, config.exchange, config.routingKey));
184
194
  // bind the exclusive queue to all the exchanges
@@ -263,8 +273,10 @@ export class RabbitMQClient {
263
273
  publishEvent: this.publishEvent.bind(this),
264
274
  };
265
275
 
266
- // send message to stream
276
+ // send message to general stream
267
277
  this.messagesStream.next(messageObj);
278
+ // send message to queue stream
279
+ this.messagesStreamsByQueue[queue]?.next(messageObj);
268
280
 
269
281
  // console.log(`Message on queue ${queue}:`, messageObj);
270
282
 
@@ -304,29 +316,35 @@ export class RabbitMQClient {
304
316
  }
305
317
  };
306
318
 
307
- const consumerTag = Date.now().toString();
319
+ this.channel.consume(queue, handleCallback, { ...(options || {}) });
320
+ }
321
+ }
308
322
 
309
- this.channel.consume(queue, handleCallback, { ...(options || {}), consumerTag: options?.consumerTag || consumerTag });
323
+ private listenToQueue(queue: string, options?: Options.Consume) {
324
+ if (this.queueListeners[queue]) {
325
+ console.log(`Already Registered messages/events listener for queue: ${queue}`);
326
+ return;
310
327
  }
328
+
329
+ console.log(`Registering messages/events listener for queue: ${queue}`);
330
+ const startQueueListener = this.getQueueListener(queue, options);
331
+
332
+ this.messagesStreamsByQueue[queue] = new Subject<RmqEventMessage>();
333
+ this.queueListeners[queue] = this.onReady.pipe(
334
+ tap((readyState) => {
335
+ startQueueListener()
336
+ })
337
+ )
338
+ .subscribe({
339
+ next: (readyState) => {
340
+ console.log(`Registered: Now listening to messages/events on queue ${queue}...`);
341
+ }
342
+ });
311
343
  }
312
344
 
313
345
  onQueue(queue: string, options?: Options.Consume) {
314
346
  // listen for messages on the queue
315
- if (!this.queueListeners[queue]) {
316
- console.log(`Registering messages/events listener for queue ${queue}:`);
317
- const startQueueListener = this.getQueueListener(queue, options);
318
-
319
- this.queueListeners[queue] = this.onReady.pipe(
320
- tap((readyState) => {
321
- startQueueListener()
322
- })
323
- )
324
- .subscribe({
325
- next: (readyState) => {
326
- console.log(`Registered: Now listening to messages/events on queue ${queue}...`);
327
- }
328
- });
329
- }
347
+ this.listenToQueue(queue, options);
330
348
 
331
349
  const handle = (messageType: string) => {
332
350
  return this.onReady.pipe(
@@ -367,6 +385,11 @@ export class RabbitMQClient {
367
385
  };
368
386
  }
369
387
 
388
+ forQueue(queue: string, options?: Options.Consume) {
389
+ this.listenToQueue(queue, options);
390
+ return this.messagesStreamsByQueue[queue].asObservable();
391
+ }
392
+
370
393
  ack(message: ConsumeMessage) {
371
394
  this.channel.ack(message);
372
395
  console.log(`Acknoledged rmq message.`);
package/src/types.ts CHANGED
@@ -11,7 +11,6 @@ import {
11
11
 
12
12
  export type MapType<T = any> = { [key:string]: T };
13
13
 
14
-
15
14
  export type RmqMessageTypeHandler = (event: RmqEventMessage) => Promise<void>;
16
15
  export type RmqHandleMessageTypeConfig = { messageName: string, callbackHandler: RmqMessageTypeHandler };
17
16
  export type RmqHandleMessageTypeConfigs = string[] | RmqHandleMessageTypeConfig[];
@@ -25,15 +24,25 @@ export interface QueueConfig {
25
24
  /*
26
25
  the event names
27
26
  */
28
- handleMessageTypes: RmqHandleMessageTypeConfigs,
27
+ handleMessageTypes?: RmqHandleMessageTypeConfigs,
29
28
 
30
29
  /*
31
30
 
32
31
  */
33
32
  options?: Options.AssertQueue
34
33
  }
35
- export interface ExchangeConfig { name: string, type: string, options?: Options.AssertExchange }
36
- export interface QueueExchangeBindingConfig { queue: string, exchange: string, routingKey: string }
34
+
35
+ export interface ExchangeConfig {
36
+ name: string,
37
+ type: string,
38
+ options?: Options.AssertExchange
39
+ }
40
+
41
+ export interface QueueExchangeBindingConfig {
42
+ queue: string,
43
+ exchange: string,
44
+ routingKey: string
45
+ }
37
46
 
38
47
  export type RmqEventRequestResponse <T = any> = Promise<RmqEventMessage<T>>;
39
48
 
@@ -68,6 +77,7 @@ export type RmqEventMessage<T = any> = {
68
77
  export type AckFn = (message: Message) => void;
69
78
 
70
79
  export type RabbitMqInitConfig = {
80
+ stopAutoInit: boolean,
71
81
  dontSendToReplyQueueOnPublish?: boolean,
72
82
  autoAckUnhandledMessageTypes?: boolean,
73
83
  pushUnhandledMessageTypesToDefaultHandler?: boolean,