rxjs-rabbitmq 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.
package/README.md ADDED
@@ -0,0 +1,99 @@
1
+ # RxJS Rabbit MQ Client
2
+
3
+
4
+
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,
17
+ ];
18
+
19
+ const rmqClient = new RabbitMQClient({
20
+ connection_url: AppEnvironment.RABBIT_MQ_URL,
21
+ delayStart: 5000,
22
+ prefetch: 5,
23
+ retryAttempts: 3,
24
+ retryDelay: 3000,
25
+ autoAckUnhandledMessageTypes: true,
26
+ queues: [
27
+ { name: MicroservicesQueues.EMAILS, handleMessageTypes, options: { durable: true } },
28
+ ],
29
+ 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 } },
33
+ ],
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
+ ]
38
+ });
39
+
40
+
41
+
42
+ const emailsQueue = rmqClient.onQueue(MicroservicesQueues.EMAILS);
43
+
44
+ emailsQueue.handle(EmailsQueueMessageTypes.SEND_EMAIL).subscribe({
45
+ next: (event: RmqEventMessage) => SEND_EMAIL(event, rmqClient)
46
+ });
47
+
48
+ emailsQueue.handle(UsersQueueEventTypes.USER_CREATED).subscribe({
49
+ next: (event: RmqEventMessage) => USER_CREATED(event, rmqClient)
50
+ });
51
+
52
+ emailsQueue.handle(UsersQueueEventTypes.USER_DELETED).subscribe({
53
+ next: (event: RmqEventMessage) => USER_DELETED(event, rmqClient)
54
+ });
55
+
56
+
57
+
58
+ /**
59
+ * Send arbitrary emails via given arguments
60
+ *
61
+ * @param event
62
+ * @param rmqClient
63
+ * @returns {void}
64
+ */
65
+ export async function SEND_EMAIL(event: RmqEventMessage, rmqClient: RabbitMQClient) {
66
+ console.log(`[${EmailsQueueMessageTypes.SEND_EMAIL}] Received message:`, { data: event.data });
67
+
68
+ const sendEmailParams = event.data as SendEmailDto;
69
+
70
+ const email_send_results: SendEmailCommandOutput = await sendAwsEmail({
71
+ to: sendEmailParams.to_email,
72
+ subject: sendEmailParams.subject,
73
+ message: sendEmailParams.text,
74
+ html: sendEmailParams.html,
75
+ });
76
+
77
+ const serviceMethodResults: ServiceMethodResults = {
78
+ status: HttpStatusCode.OK,
79
+ error: false,
80
+ info: {
81
+ data: email_send_results
82
+ }
83
+ };
84
+
85
+ rmqClient.ack(event.message);
86
+ return rmqClient.publishEvent({
87
+ exchange: MicroservicesExchanges.EMAIL_EVENTS,
88
+ routingKey: RoutingKeys.EVENT,
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,
95
+ }
96
+ });
97
+ }
98
+
99
+ ```
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "rxjs-rabbitmq",
3
+ "version": "1.0.0",
4
+ "description": "RxJS powered RabbitMQ event handling",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "deprecated": false,
8
+ "homepage": "https://github.com/ryanwaite28/rxjs-rabbitmq",
9
+ "scripts": {
10
+ "tsc": "tsc",
11
+ "build": "tsc",
12
+ "prepublish": "tsc",
13
+ "test": "echo \"Error: no test specified\" && exit 1"
14
+ },
15
+ "author": "Ryan M. Waite",
16
+ "license": "ISC",
17
+ "devDependencies": {
18
+ "@types/amqplib": "^0.10.1",
19
+ "@types/node": "^20.6.2",
20
+ "tslint": "^6.1.3",
21
+ "typescript": "^5.2.2"
22
+ },
23
+ "dependencies": {
24
+ "amqplib": "^0.10.3",
25
+ "rxjs": "^7.8.1",
26
+ "uuid": "^9.0.1"
27
+ },
28
+ "keywords": [
29
+ "RxJS",
30
+ "RabbitMQ",
31
+ "amqplib"
32
+ ],
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/ryanwaite28/rxjs-rabbitmq.git"
36
+ }
37
+ }
package/src/enums.ts ADDED
@@ -0,0 +1,80 @@
1
+ export enum ContentTypes {
2
+ JSON = 'application/json',
3
+ TEXT = 'text/plain',
4
+ STREAM = 'application/octet-stream'
5
+ }
6
+
7
+ export enum MimeTypes {
8
+ AAC = "audio/aac",
9
+ ABW = "application/x-abiword",
10
+ ARC = "application/x-freearc",
11
+ AVI = "video/x-msvideo",
12
+ AZW = "application/vnd.amazon.ebook",
13
+ BIN = "application/octet-stream",
14
+ BMP = "image/bmp",
15
+ BZ = "application/x-bzip",
16
+ BZ2 = "application/x-bzip2",
17
+ CSH = "application/x-csh",
18
+ CSS = "text/css",
19
+ CSV = "text/csv",
20
+ DOC = "application/msword",
21
+ DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
22
+ EOT = "application/vnd.ms-fontobject",
23
+ EPUB = "application/epub+zip",
24
+ GZ = "application/gzip",
25
+ GIF = "image/gif",
26
+ HTM = "text/html",
27
+ HTML = "text/html",
28
+ ICO = "image/vnd.microsoft.icon",
29
+ ICS = "text/calendar",
30
+ JAR = "application/java-archive",
31
+ JPEG = "jpg",
32
+ JS = "text/javascript",
33
+ JSON = "application/json",
34
+ JSONLD = "application/ld+json",
35
+ MID = ".midi",
36
+ MJS = "text/javascript",
37
+ MP3 = "audio/mpeg",
38
+ MPEG = "video/mpeg",
39
+ MPKG = "application/vnd.apple.installer+xml",
40
+ ODP = "application/vnd.oasis.opendocument.presentation",
41
+ ODS = "application/vnd.oasis.opendocument.spreadsheet",
42
+ ODT = "application/vnd.oasis.opendocument.text",
43
+ OGA = "audio/ogg",
44
+ OGV = "video/ogg",
45
+ OGX = "application/ogg",
46
+ OPUS = "audio/opus",
47
+ OTF = "font/otf",
48
+ PNG = "image/png",
49
+ PDF = "application/pdf",
50
+ PHP = "application/php",
51
+ PPT = "application/vnd.ms-powerpoint",
52
+ PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation",
53
+ RAR = "application/vnd.rar",
54
+ RTF = "application/rtf",
55
+ SH = "application/x-sh",
56
+ SVG = "image/svg+xml",
57
+ SWF = "application/x-shockwave-flash",
58
+ TAR = "application/x-tar",
59
+ TIF = "image/tiff",
60
+ TIFF = "image/tiff",
61
+ TS = "video/mp2t",
62
+ TTF = "font/ttf",
63
+ TXT = "text/plain",
64
+ VSD = "application/vnd.visio",
65
+ WAV = "audio/wav",
66
+ WEBA = "audio/webm",
67
+ WEBM = "video/webm",
68
+ WEBP = "image/webp",
69
+ WOFF = "font/woff",
70
+ WOFF2 = "font/woff2",
71
+ XHTML = "application/xhtml+xml",
72
+ XLS = "application/vnd.ms-excel",
73
+ XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
74
+ XML = "XML",
75
+ XUL = "application/vnd.mozilla.xul+xml",
76
+ ZIP = "application/zip",
77
+ VIDEO_3GP = "video/3gpp",
78
+ VIDEO_3G2 = "video/3gpp2",
79
+ COMPRESS_7Z = "application/x-7z-compressed"
80
+ }
@@ -0,0 +1,481 @@
1
+ import { v1 as uuidv1 } from 'uuid';
2
+
3
+ import {
4
+ Connection,
5
+ Channel,
6
+ Replies,
7
+ connect,
8
+ Options,
9
+ ConsumeMessage
10
+ } from "amqplib";
11
+
12
+ import {
13
+ BehaviorSubject,
14
+ filter,
15
+ firstValueFrom,
16
+ map,
17
+ mergeMap,
18
+ Observable,
19
+ ReplaySubject,
20
+ Subject,
21
+ Subscription,
22
+ take,
23
+ tap,
24
+ } from "rxjs";
25
+
26
+ import {
27
+ mapify,
28
+ SERIALIZERS,
29
+ uniqueValue,
30
+ wait
31
+ } from "./utils";
32
+
33
+ import {
34
+ MapType,
35
+ QueueExchangeBindingConfig,
36
+ RabbitMqInitConfig,
37
+ RmqEventMessage,
38
+ RmqHandleMessageTypeConfig,
39
+ RmqMessageTypeHandler,
40
+ RmqPublishEventParams,
41
+ RmqSendMessageParams
42
+ } from "./types";
43
+
44
+ import { ContentTypes } from "./enums";
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+ export class RabbitMQClient {
53
+ private clientInitConfig: RabbitMqInitConfig;
54
+
55
+ private connection: Connection;
56
+ private channel: Channel;
57
+ private isReady: boolean = false;
58
+ private isReadyStream: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(this.isReady);
59
+ private connectionErrorStream: Subject<any> = new Subject<any>();
60
+ private connectionCloseStream: Subject<any> = new Subject<any>();
61
+
62
+ private queues: MapType<Replies.AssertQueue> = {};
63
+ private exchanges:MapType<Replies.AssertExchange> = {};
64
+ private bindings: QueueExchangeBindingConfig[] = [];
65
+
66
+ private DEFAULT_LISTENER_TYPE = '__default';
67
+
68
+ private EXCLUSIVE_QUEUE: string = uuidv1();
69
+
70
+ private queueListeners: MapType<Subscription> = {};
71
+
72
+ private queueToEventHandleMapping: MapType<
73
+ MapType<ReplaySubject<RmqEventMessage>>
74
+ > = {};
75
+ private queueToEventCallbackMapping: MapType<
76
+ MapType<RmqMessageTypeHandler>
77
+ > = {};
78
+
79
+ get onReady(): Observable<boolean> {
80
+ return this.isReadyStream.asObservable().pipe(
81
+ filter((state) => !!state),
82
+ take(1)
83
+ );
84
+ }
85
+
86
+ get onConnectionError(): Observable<any> {
87
+ return this.connectionErrorStream.asObservable();
88
+ }
89
+
90
+ get onConnectionClose(): Observable<any> {
91
+ return this.connectionCloseStream.asObservable();
92
+ }
93
+
94
+ constructor(clientInitConfig: RabbitMqInitConfig) {
95
+ this.init(clientInitConfig);
96
+ }
97
+
98
+ init(clientInitConfig: RabbitMqInitConfig) {
99
+ this.clientInitConfig = clientInitConfig;
100
+ const {
101
+ delayStart,
102
+ connection_url,
103
+ prefetch,
104
+ queues,
105
+ exchanges,
106
+ bindings,
107
+ pre_init_promises,
108
+ post_init_promises
109
+ } = clientInitConfig;
110
+
111
+ let retryAttempts = clientInitConfig.retryAttempts || 0;
112
+ const retryDelay = clientInitConfig.retryDelay || 0;
113
+
114
+ const init = () => {
115
+ console.log(`Attempting connection to Rabbit MQ...`);
116
+ return connect(connection_url)
117
+ .then((connection) => {
118
+ this.connection = connection;
119
+ console.log(`connected to message server`);
120
+ return this.connection.createChannel();
121
+ })
122
+ .then((channel) => {
123
+ this.channel = channel;
124
+ if (prefetch) {
125
+ this.channel.prefetch(prefetch || 1);
126
+ }
127
+ console.log(`channel created on message server`);
128
+ })
129
+ .then(() => {
130
+ // create an exclusive queue for this channel connection
131
+ console.log(`Creating exclusive queue ${this.EXCLUSIVE_QUEUE}`);
132
+ return this.channel.assertQueue(this.EXCLUSIVE_QUEUE, { exclusive: true, durable: false }).then((response) => {
133
+ console.log(`Created exclusive queue ${this.EXCLUSIVE_QUEUE}`);
134
+ });
135
+ })
136
+ .then(() => {
137
+ const promises: Promise<Replies.AssertQueue>[] = [];
138
+ // by default, create an observable stream on the queue for unidentified/null routing keys
139
+ for (const queueConfig of queues) {
140
+ this.queueToEventHandleMapping[queueConfig.name] = {};
141
+ this.queueToEventCallbackMapping[queueConfig.name] = {};
142
+
143
+ const queueListenersMap = this.queueToEventHandleMapping[queueConfig.name];
144
+ const queueCallbacksMap = this.queueToEventCallbackMapping[queueConfig.name];
145
+
146
+ queueListenersMap[this.DEFAULT_LISTENER_TYPE] = new ReplaySubject();
147
+
148
+ const isStringList = typeof queueConfig.handleMessageTypes[0] === 'string';
149
+ if (isStringList) {
150
+ for (const messageType of queueConfig.handleMessageTypes) {
151
+ queueListenersMap[messageType as string] = new ReplaySubject();
152
+ }
153
+ }
154
+ else {
155
+ for (const messageType of queueConfig.handleMessageTypes) {
156
+ const config: RmqHandleMessageTypeConfig = (messageType as any) as RmqHandleMessageTypeConfig;
157
+ queueCallbacksMap[config.messageType] = config.callbackHandler;
158
+ }
159
+ this.onQueue(queueConfig.name);
160
+ }
161
+
162
+ promises.push(this.channel.assertQueue(queueConfig.name, queueConfig.options));
163
+ }
164
+ return Promise.all(promises).then((values) => {
165
+ this.queues = mapify(values, 'queue');
166
+ console.log(`queues created on channel`);
167
+ })
168
+ })
169
+ .then(() => {
170
+ const promises = exchanges.map((config) => this.channel.assertExchange(config.name, config.type, config.options));
171
+ return Promise.all(promises).then(values => {
172
+ this.exchanges = mapify(values, 'exchange');
173
+ console.log(`exchanges created on channel`);
174
+ });
175
+ })
176
+ .then(() => {
177
+ const promises = bindings.map((config) => this.channel.bindQueue(config.queue, config.exchange, config.routingKey));
178
+ // bind the exclusive queue to all the exchanges
179
+ // const exclusiveBindings = bindings.map((config) => this.channel.bindQueue(this.EXCLUSIVE_QUEUE, config.exchange, config.routingKey));
180
+ return Promise.all(promises).then(values => {
181
+ console.log(`bindings created on channel`);
182
+ });
183
+ })
184
+ .then(() => {
185
+ console.log(`Client initialization complete; waiting for messages/events...\n`);
186
+
187
+ // initialization complete; listen for connection issues to retry again
188
+ retryAttempts = clientInitConfig.retryAttempts;
189
+
190
+ this.connection.on("error", (err) => {
191
+ this.connectionErrorStream.next(err);
192
+ });
193
+ this.connection.on("close", (err) => {
194
+ this.connectionErrorStream.next(err);
195
+ });
196
+
197
+ this.isReady = true;
198
+ this.isReadyStream.next(true);
199
+ })
200
+
201
+ .catch((error) => {
202
+ console.log(`connection error, retryAttempts: ${retryAttempts}`, error);
203
+ if (retryAttempts === 0) {
204
+ console.log(`all retry attemptys exhaused; exiting...`);
205
+ throw error;
206
+ }
207
+ retryAttempts = retryAttempts - 1;
208
+ return wait(retryDelay).then(init);
209
+ });
210
+ };
211
+
212
+ return wait(delayStart || 0)
213
+ .then(() => {
214
+ console.log(`Running pre init promises...`);
215
+ return Promise.all(pre_init_promises?.map(p => p instanceof Promise ? p : p()) || []).then(() => {
216
+ console.log(`Done running pre init promises.\n`);
217
+ });
218
+ })
219
+ .then(init)
220
+ .then(() => {
221
+ console.log(`Running post init promises...`);
222
+ return Promise.all(post_init_promises?.map(p => p instanceof Promise ? p : p()) || []).then(() => {
223
+ console.log(`Done running post init promises. `);
224
+ });
225
+ });
226
+ }
227
+
228
+ getConnection() {
229
+ return this.onReady.pipe(map(() => this.connection));
230
+ }
231
+
232
+ getChannel() {
233
+ return this.onReady.pipe(map(() => this.channel));
234
+ }
235
+
236
+ onQueue(queue: string, options?: Options.Consume) {
237
+ // listen for messages on the queue
238
+ if (!this.queueListeners[queue]) {
239
+ console.log(`Registering messages/events listener for queue ${queue}:`);
240
+ const startQueueListener = () => {
241
+ const handleCallback = (message: ConsumeMessage | null) => {
242
+ if (!message) {
243
+ throw new Error('Consumer cancelled by server');
244
+ }
245
+
246
+ console.log(`received queue message`, message);
247
+
248
+ // see if a listener was created for the routing key
249
+ const messageType = message.properties.type;
250
+ const useContentType = message.properties.contentType;
251
+ const useData = SERIALIZERS[useContentType] ? SERIALIZERS[useContentType].deserialize(message.content) : message.content;
252
+ const messageObj: RmqEventMessage = {
253
+ data: useData,
254
+ message,
255
+ ack: () => {
256
+ this.ack(message);
257
+ },
258
+ sendMessage: this.sendMessage.bind(this),
259
+ sendRequest: this.sendRequest.bind(this),
260
+ publishEvent: this.publishEvent.bind(this),
261
+ };
262
+
263
+ // console.log(`Message on queue ${queue}:`, messageObj);
264
+
265
+ if (!messageType) {
266
+ // no type key found, push to default stream
267
+ console.log(`No message type found; pushing to default handler on queue ${queue}`);
268
+ this.queueToEventHandleMapping[queue][this.DEFAULT_LISTENER_TYPE].next(messageObj);
269
+ }
270
+ else {
271
+ // type key found
272
+ if (this.queueToEventHandleMapping[queue][messageType]) {
273
+ // there is a registered listener for the type, push to that stream
274
+ console.log(`message type handler found; pushing to ${messageType} handler on queue ${queue}`);
275
+ this.queueToEventHandleMapping[queue][messageType].next(messageObj);
276
+ }
277
+ else if (this.queueToEventCallbackMapping[queue][messageType]) {
278
+ // there is a registered listener for the type, push to that stream
279
+ console.log(`message type callback found; pushing to ${messageType} callback on queue ${queue}`);
280
+ const callbackHandler = this.queueToEventCallbackMapping[queue][messageType];
281
+ callbackHandler(messageObj);
282
+ }
283
+ else {
284
+ // no registered listener
285
+ if (this.clientInitConfig.autoAckUnhandledMessageTypes) {
286
+ console.log(`No handler found for message type ${messageType} on queue ${queue}; auto acknowledging.`);
287
+ this.ack(message);
288
+ return;
289
+ }
290
+ else if (this.clientInitConfig.pushUnhandledMessageTypesToDefaultHandler) {
291
+ console.log(`No handler found for message type ${messageType} on queue ${queue}; pushing to ${this.DEFAULT_LISTENER_TYPE} handler.`);
292
+ this.queueToEventHandleMapping[queue][this.DEFAULT_LISTENER_TYPE].next(messageObj);
293
+ return;
294
+ }
295
+ else {
296
+ 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.`);
297
+ }
298
+ }
299
+ }
300
+ };
301
+
302
+ const consumerTag = Date.now().toString();
303
+
304
+ this.channel.consume(queue, handleCallback, { ...(options || {}), consumerTag: options?.consumerTag || consumerTag });
305
+ }
306
+
307
+ this.queueListeners[queue] = this.onReady.pipe(tap((readyState) => startQueueListener())).subscribe({
308
+ next: (readyState) => {
309
+ console.log(`Registered: Now listening to messages/events on queue ${queue}...`);
310
+ }
311
+ });
312
+ }
313
+
314
+ const handle = (messageType: string) => {
315
+ return this.onReady.pipe(
316
+ mergeMap((ready: boolean, index: number) => {
317
+ if (!this.queueToEventHandleMapping[queue][messageType]) {
318
+ 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.`);
319
+ }
320
+ return this.queueToEventHandleMapping[queue][messageType].asObservable();
321
+ })
322
+ );
323
+ };
324
+
325
+ const handleDefault = () => {
326
+ return this.onReady.pipe(
327
+ mergeMap((ready: boolean, index: number) => this.queueToEventHandleMapping[queue][this.DEFAULT_LISTENER_TYPE].asObservable())
328
+ );
329
+ };
330
+
331
+ return {
332
+ handle,
333
+ handleDefault
334
+ };
335
+ }
336
+
337
+ ack(message: ConsumeMessage) {
338
+ this.channel.ack(message);
339
+ console.log(`Acknoledged rmq message.`);
340
+ }
341
+
342
+ sendMessage(options: RmqSendMessageParams) {
343
+ return new Promise((resolve, reject) => {
344
+ const send = () => {
345
+ const { data, publishOptions, queue } = options;
346
+ const useContentType = publishOptions.contentType || ContentTypes.TEXT;
347
+ const useData = SERIALIZERS[useContentType] ? SERIALIZERS[useContentType].serialize(data) : data;
348
+ this.channel.sendToQueue(queue, useData, { ...publishOptions, appId: publishOptions.appId });
349
+ resolve(undefined);
350
+ };
351
+
352
+ if (!this.isReady) {
353
+ console.log(`wait until ready to send message...`);
354
+ firstValueFrom(this.onReady).then((readyState) => {
355
+ console.log(`now ready to send message`, { readyState });
356
+ send();
357
+ });
358
+ }
359
+ else {
360
+ console.log(`is ready to send message`);
361
+ send();
362
+ }
363
+ });
364
+ }
365
+
366
+ sendRequest <T = any> (options: {
367
+ queue: string,
368
+ data: any,
369
+ publishOptions: Options.Publish,
370
+ }) {
371
+ console.log(`sendRequest:`, options);
372
+
373
+ return new Promise<RmqEventMessage<T>>(async (resolve, reject) => {
374
+ const start_time = Date.now();
375
+
376
+ const consumerTag = uniqueValue();
377
+ const correlationId = options.publishOptions.correlationId || uniqueValue();
378
+ const temporaryRpcQueue = uuidv1();
379
+
380
+ const newQueue = await this.channel.assertQueue(temporaryRpcQueue, { exclusive: true, durable: false, autoDelete: true }).then((response) => {
381
+ console.log(`Created temp queue ${temporaryRpcQueue} for client.`);
382
+ return response;
383
+ });
384
+
385
+ const send = () => {
386
+ const { data, publishOptions, queue } = options;
387
+ const useContentType = publishOptions.contentType || ContentTypes.TEXT;
388
+ const useData = SERIALIZERS[useContentType] ? SERIALIZERS[useContentType].serialize(data) : data;
389
+ this.channel.sendToQueue(queue, useData, { ...publishOptions, correlationId, replyTo: temporaryRpcQueue, appId: publishOptions.appId });
390
+ };
391
+
392
+ const watch = () => {
393
+ console.log(`request/rpc sent; awaiting response...`, { correlationId, consumerTag });
394
+
395
+ const replyHandler = (message: ConsumeMessage | null) => {
396
+ console.log(`\nReceived reply.\n`, { message });
397
+ const correlationIdMatch = message!.properties.correlationId == correlationId;
398
+ const isReplyToRequest: boolean = !!message && correlationIdMatch;
399
+ console.log({ isReplyToRequest, consumerTag, correlationIdMatch, requestCorrelationId: correlationId, responseCorrelationId: message!.properties.correlationId });
400
+
401
+ if (isReplyToRequest) {
402
+ this.ack(message!);
403
+ const useContentType = message!.properties.contentType;
404
+ const useData = SERIALIZERS[useContentType] ? SERIALIZERS[useContentType].deserialize(message!.content) : message!.content;
405
+ const messageObj: RmqEventMessage = {
406
+ data: useData,
407
+ message: message!,
408
+ ack: () => {
409
+ this.ack(message!);
410
+ },
411
+ sendMessage: this.sendMessage.bind(this),
412
+ sendRequest: this.sendRequest.bind(this),
413
+ publishEvent: this.publishEvent.bind(this),
414
+ };
415
+ const end_time = Date.now();
416
+ const total_time = (end_time - start_time) / 1000;
417
+ const time_in_seconds = total_time.toFixed();
418
+ console.log(`received response from request/rpc:`, { start_time, end_time, total_time, time_in_seconds, messageObj, options });
419
+ resolve(messageObj);
420
+ this.channel.cancel(consumerTag).then(() => {
421
+ console.log(`removed consumer via consumerTag`);
422
+ });
423
+ }
424
+ };
425
+
426
+ this.channel.consume(temporaryRpcQueue, replyHandler, { consumerTag });
427
+ };
428
+
429
+ if (!this.isReady) {
430
+ console.log(`waiting until ready to send request`);
431
+ firstValueFrom(this.onReady).then((readyState) => {
432
+ console.log(`now ready to publish event`, { readyState });
433
+ watch(); // first listen on the reply queue
434
+ send(); // then send the rpc/rmq message
435
+ });
436
+ }
437
+ else {
438
+ console.log(`is ready to send request`);
439
+ watch();
440
+ send();
441
+ }
442
+ });
443
+ }
444
+
445
+ publishEvent(options: RmqPublishEventParams) {
446
+ const publish = () => {
447
+ const { data, routingKey, publishOptions, exchange } = options;
448
+ const useContentType = publishOptions.contentType || ContentTypes.TEXT;
449
+ const useData = SERIALIZERS[useContentType] ? SERIALIZERS[useContentType].serialize(data) : data;
450
+ this.channel.publish(exchange, routingKey, useData, { ...publishOptions, appId: publishOptions.appId });
451
+
452
+ if (publishOptions.replyTo && !this.clientInitConfig.dontSendToReplyQueueOnPublish) {
453
+ console.log(`sending copy to reply to queue ${publishOptions.replyTo}...`);
454
+ this.channel.sendToQueue(publishOptions.replyTo, useData, publishOptions);
455
+ }
456
+ };
457
+
458
+ if (!this.isReady) {
459
+ console.log(`wait until ready to publish event`);
460
+ this.onReady.subscribe({
461
+ next: (readyState) => {
462
+ console.log(`now ready to publish event`, { readyState });
463
+ readyState && publish();
464
+ }
465
+ });
466
+ }
467
+ else {
468
+ console.log(`is ready to publish event`);
469
+ publish();
470
+ }
471
+ }
472
+
473
+ listen() {
474
+ // last resort to keeping the node.js process running
475
+ const listenerCallback = () => {
476
+ console.log(`--- listening... ---`);
477
+ };
478
+ const interval = setInterval(listenerCallback, 1000 * 60 * 10);
479
+ return interval;
480
+ }
481
+ }
package/src/types.ts ADDED
@@ -0,0 +1,67 @@
1
+ import {
2
+ Options,
3
+ ConsumeMessage,
4
+ Message
5
+ } from "amqplib";
6
+
7
+
8
+
9
+ export type MapType<T = any> = { [key:string]: T };
10
+
11
+
12
+ export type RmqMessageTypeHandler = (event: RmqEventMessage) => Promise<void>;
13
+ export type RmqHandleMessageTypeConfig = { messageType: string, callbackHandler: RmqMessageTypeHandler };
14
+ export type RmqHandleMessageTypeConfigs = string[] | RmqHandleMessageTypeConfig[];
15
+
16
+ export interface QueueConfig { name: string, handleMessageTypes: RmqHandleMessageTypeConfigs, options?: Options.AssertQueue }
17
+ export interface ExchangeConfig { name: string, type: string, options?: Options.AssertExchange }
18
+ export interface QueueExchangeBindingConfig { queue: string, exchange: string, routingKey: string }
19
+
20
+ export type RmqEventRequestResponse <T = any> = Promise<RmqEventMessage<T>>;
21
+
22
+ export type RmqSendMessageParams = {
23
+ queue: string,
24
+ data: any,
25
+ publishOptions: Options.Publish
26
+ }
27
+
28
+ export type RmqSendRequestParams = {
29
+ queue: string,
30
+ data: any,
31
+ publishOptions: Options.Publish,
32
+ }
33
+
34
+ export type RmqPublishEventParams<T = any> = {
35
+ exchange: string,
36
+ data: T,
37
+ routingKey: string,
38
+ publishOptions: Options.Publish
39
+ }
40
+
41
+ export type RmqEventMessage<T = any> = {
42
+ data: T,
43
+ message: ConsumeMessage,
44
+ ack: () => void;
45
+ publishEvent: (options: RmqPublishEventParams) => void,
46
+ sendMessage: (options: RmqSendMessageParams) => void,
47
+ sendRequest: <T = any> (options: RmqSendRequestParams) => Promise<RmqEventMessage<T>>,
48
+ };
49
+
50
+ export type AckFn = (message: Message) => void;
51
+
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
+ queues: Array<QueueConfig>,
62
+ exchanges: Array<ExchangeConfig>,
63
+ bindings: Array<QueueExchangeBindingConfig>,
64
+
65
+ pre_init_promises?: (Promise<any> | (() => Promise<any>))[],
66
+ post_init_promises?: (Promise<any> | (() => Promise<any>))[],
67
+ };
package/src/utils.ts ADDED
@@ -0,0 +1,55 @@
1
+ import { MapType } from "./types";
2
+
3
+ // https://github.com/Foo-Foo-MQ/foo-foo-mq/blob/main/src/index.js
4
+ export const SERIALIZERS = {
5
+ 'application/json': {
6
+ deserialize: (bytes: any, encoding: any) => {
7
+ return JSON.parse(bytes.toString(encoding || 'utf8'));
8
+ },
9
+ serialize: (object: any) => {
10
+ const json = (typeof object === 'string')
11
+ ? object
12
+ : JSON.stringify(object);
13
+ return Buffer.from(json, 'utf8');
14
+ }
15
+ },
16
+ 'application/octet-stream': {
17
+ deserialize: (bytes: any) => {
18
+ return bytes;
19
+ },
20
+ serialize: (bytes: any) => {
21
+ if (Buffer.isBuffer(bytes)) {
22
+ return bytes;
23
+ } else if (Array.isArray(bytes)) {
24
+ return Buffer.from(bytes);
25
+ } else {
26
+ throw new Error('Cannot serialize unknown data type');
27
+ }
28
+ }
29
+ },
30
+ 'text/plain': {
31
+ deserialize: (bytes: any, encoding: any) => {
32
+ return bytes.toString(encoding || 'utf8');
33
+ },
34
+ serialize: (str: string) => {
35
+ return Buffer.from(str, 'utf8');
36
+ }
37
+ }
38
+ };
39
+
40
+ export const mapify = <T> (list: T[], key: string | number): MapType<T> => {
41
+ return list.reduce((map: MapType<T>, item: T) => {
42
+ map[ item[key] ] = item;
43
+ return map;
44
+ }, {} as MapType<T>);
45
+ };
46
+
47
+ export const wait = (time) => {
48
+ return new Promise((resolve) => {
49
+ setTimeout(resolve, time);
50
+ });
51
+ };
52
+
53
+ export function uniqueValue() {
54
+ return Math.random().toString(33).substring(2) + '-' + Date.now();
55
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,114 @@
1
+ {
2
+ "compileOnSave": false,
3
+ "types": [
4
+ "node"
5
+ ],
6
+ "typeRoots": ["node_modules/@types"],
7
+ "exclude": ["node_modules"],
8
+ "include": ["src/**/*"],
9
+ "compilerOptions": {
10
+ /* Visit https://aka.ms/tsconfig to read more about this file */
11
+
12
+ /* Projects */
13
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
14
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
15
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
16
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
17
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
18
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
19
+
20
+ /* Language and Environment */
21
+ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
22
+ "lib": ["es2017"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
23
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
24
+ "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
25
+ "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
26
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
27
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
28
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
29
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
30
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
31
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
32
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
33
+
34
+ /* Modules */
35
+ "module": "esnext", /* Specify what module code is generated. */
36
+ // "rootDir": "./src", /* Specify the root folder within your source files. */
37
+ "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
38
+ "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
39
+ "paths": {
40
+ // "@lib/frontend-shared": ["src/lib/frontend-shared"],
41
+ // "@lib/backend-shared": ["src/lib/backend-shared"],
42
+ // "@lib/fullstack-shared": ["src/lib/fullstack-shared"],
43
+ }, /* Specify a set of entries that re-map imports to additional lookup locations. */
44
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
45
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
46
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
47
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
48
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
49
+ // "resolveJsonModule": true, /* Enable importing .json files. */
50
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
51
+
52
+ /* JavaScript Support */
53
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
54
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
55
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
56
+
57
+ /* Emit */
58
+ "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
59
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
60
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
61
+ "sourceMap": true, /* Create source map files for emitted JavaScript files. */
62
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
63
+ "outDir": "./dist", /* Specify an output folder for all emitted files. */
64
+ // "removeComments": true, /* Disable emitting comments. */
65
+ // "noEmit": true, /* Disable emitting files from a compilation. */
66
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
67
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
68
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
69
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
70
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
71
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
72
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
73
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
74
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
75
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
76
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
77
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
78
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
79
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
80
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
81
+
82
+ /* Interop Constraints */
83
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
84
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
85
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
86
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
87
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
88
+
89
+ /* Type Checking */
90
+ "strict": true, /* Enable all strict type-checking options. */
91
+ "noImplicitAny": false, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
92
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
93
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
94
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
95
+ "strictPropertyInitialization": false, /* Check for class properties that are declared but not set in the constructor. */
96
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
97
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
98
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
99
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
100
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
101
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
102
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
103
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
104
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
105
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
106
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
107
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
108
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
109
+
110
+ /* Completeness */
111
+ "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
112
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
113
+ }
114
+ }
package/tslint.json ADDED
@@ -0,0 +1,121 @@
1
+ {
2
+ "rules": {
3
+ "arrow-return-shorthand": true,
4
+ "callable-types": true,
5
+ "class-name": true,
6
+ "comment-format": [
7
+ true,
8
+ "check-space"
9
+ ],
10
+ "curly": true,
11
+ "deprecation": {
12
+ "severity": "warn"
13
+ },
14
+ "eofline": true,
15
+ "forin": true,
16
+ "import-spacing": true,
17
+ "indent": [
18
+ true,
19
+ "spaces"
20
+ ],
21
+ "interface-over-type-literal": true,
22
+ "label-position": true,
23
+ "max-line-length": [
24
+ false,
25
+ 160
26
+ ],
27
+ "member-access": false,
28
+ "member-ordering": [
29
+ true,
30
+ {
31
+ "order": [
32
+ "static-field",
33
+ "instance-field",
34
+ "static-method",
35
+ "instance-method"
36
+ ]
37
+ }
38
+ ],
39
+ "no-arg": true,
40
+ "no-bitwise": true,
41
+ "no-console": [
42
+ true,
43
+ "debug",
44
+ "info",
45
+ "time",
46
+ "timeEnd",
47
+ "trace"
48
+ ],
49
+ "no-construct": true,
50
+ "no-debugger": true,
51
+ "no-duplicate-super": true,
52
+ "no-empty": false,
53
+ "no-empty-interface": true,
54
+ "no-eval": true,
55
+ "no-misused-new": true,
56
+ "no-non-null-assertion": true,
57
+ "no-shadowed-variable": true,
58
+ "no-string-literal": false,
59
+ "no-string-throw": true,
60
+ "no-switch-case-fall-through": true,
61
+ "no-trailing-whitespace": true,
62
+ "no-unnecessary-initializer": true,
63
+ "no-unused-expression": true,
64
+ "no-var-keyword": true,
65
+ "object-literal-sort-keys": false,
66
+ "one-line": [
67
+ true,
68
+ "check-open-brace",
69
+ "check-catch",
70
+ "check-else",
71
+ "check-whitespace"
72
+ ],
73
+ "quotemark": [
74
+ true,
75
+ "single"
76
+ ],
77
+ "semicolon": [
78
+ true,
79
+ "always"
80
+ ],
81
+ "triple-equals": [
82
+ true,
83
+ "allow-null-check"
84
+ ],
85
+ "typedef-whitespace": [
86
+ false,
87
+ {
88
+ "call-signature": "nospace",
89
+ "index-signature": "nospace",
90
+ "parameter": "nospace",
91
+ "property-declaration": "nospace",
92
+ "variable-declaration": "nospace"
93
+ }
94
+ ],
95
+ "typeof-compare": true,
96
+ "unified-signatures": true,
97
+ "variable-name": false,
98
+ "directive-selector": [
99
+ true,
100
+ "attribute",
101
+ "app",
102
+ "camelCase"
103
+ ],
104
+ "component-selector": [
105
+ true,
106
+ "element",
107
+ "app",
108
+ "kebab-case"
109
+ ],
110
+ "no-output-on-prefix": true,
111
+ "no-inputs-metadata-property": true,
112
+ "no-outputs-metadata-property": true,
113
+ "no-host-metadata-property": true,
114
+ "no-input-rename": true,
115
+ "no-output-rename": true,
116
+ "use-lifecycle-interface": true,
117
+ "use-pipe-transform-interface": true,
118
+ "component-class-suffix": true,
119
+ "directive-class-suffix": true
120
+ }
121
+ }