|
1 |
| -import amqp, { Connection, Channel } from "amqplib/callback_api"; |
| 1 | +import { |
| 2 | + connect as amqplibConnect, |
| 3 | + Options, |
| 4 | + ChannelModel, |
| 5 | + Channel, |
| 6 | +} from "amqplib"; |
2 | 7 | import {
|
3 | 8 | Injectable,
|
4 | 9 | Logger,
|
5 | 10 | OnModuleDestroy,
|
6 | 11 | OnApplicationShutdown,
|
| 12 | + OnModuleInit, |
7 | 13 | } from "@nestjs/common";
|
8 | 14 | import { ConfigService } from "@nestjs/config";
|
9 | 15 |
|
| 16 | +function OnError(action: "throw" | "log" = "throw"): MethodDecorator { |
| 17 | + return function ( |
| 18 | + target: object, |
| 19 | + propertyKey: string | symbol, |
| 20 | + descriptor: PropertyDescriptor, |
| 21 | + ) { |
| 22 | + const originalMethod = descriptor.value; |
| 23 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 24 | + descriptor.value = async function (...args: any[]) { |
| 25 | + try { |
| 26 | + return await originalMethod.apply(this, args); |
| 27 | + } catch (error) { |
| 28 | + if (action === "log") { |
| 29 | + Logger.error( |
| 30 | + (this as RabbitMQService)._error + |
| 31 | + JSON.stringify((error as Error).message), |
| 32 | + "RabbitMQService", |
| 33 | + ); |
| 34 | + } else { |
| 35 | + throw new Error((this as RabbitMQService)._error, { cause: error }); |
| 36 | + } |
| 37 | + } |
| 38 | + }; |
| 39 | + return descriptor; |
| 40 | + }; |
| 41 | +} |
| 42 | + |
10 | 43 | /**
|
11 | 44 | * Service for publishing messages to a RabbitMQ queue.
|
12 | 45 | */
|
13 | 46 | @Injectable()
|
14 |
| -export class RabbitMQService implements OnModuleDestroy, OnApplicationShutdown { |
15 |
| - private connectionOptions: amqp.Options.Connect; |
16 |
| - private connection: Connection; |
| 47 | +export class RabbitMQService |
| 48 | + implements OnModuleInit, OnModuleDestroy, OnApplicationShutdown |
| 49 | +{ |
| 50 | + private connection: ChannelModel; |
17 | 51 | private channel: Channel;
|
| 52 | + private static readonly configKeys = [ |
| 53 | + "hostname", |
| 54 | + "port", |
| 55 | + "username", |
| 56 | + "password", |
| 57 | + ] as const; |
| 58 | + private connectionOptions: Required< |
| 59 | + Pick< |
| 60 | + Options.Connect, |
| 61 | + (typeof RabbitMQService.configKeys)[number] | "protocol" |
| 62 | + > |
| 63 | + >; |
| 64 | + _error: string; |
18 | 65 |
|
19 |
| - constructor(private readonly configService: ConfigService) { |
20 |
| - Logger.log("Initializing RabbitMQService.", "RabbitMQService"); |
21 |
| - |
22 |
| - const hostname = this.configService.get<string>("rabbitMq.hostname"); |
23 |
| - const port = this.configService.get<number>("rabbitMq.port"); |
24 |
| - const username = this.configService.get<string>("rabbitMq.username"); |
25 |
| - const password = this.configService.get<string>("rabbitMq.password"); |
| 66 | + constructor(private readonly configService: ConfigService) {} |
26 | 67 |
|
27 |
| - if (!hostname || !port || !username || !password) { |
28 |
| - Logger.error( |
29 |
| - "RabbitMQ is enabled but missing one or more config variables.", |
30 |
| - "RabbitMQService", |
| 68 | + getValueFromConfig(key: string): string | number { |
| 69 | + const configValue = this.configService.get(`rabbitMq.${key}`); |
| 70 | + if (!configValue) |
| 71 | + throw new Error( |
| 72 | + `RabbitMQ is enabled but missing the config variable ${key}.`, |
31 | 73 | );
|
32 |
| - } else { |
33 |
| - this.connectionOptions = { |
34 |
| - protocol: "amqp", |
35 |
| - hostname: hostname, |
36 |
| - port: port, |
37 |
| - username: username, |
38 |
| - password: password, |
39 |
| - }; |
| 74 | + return configValue; |
| 75 | + } |
40 | 76 |
|
41 |
| - amqp.connect( |
42 |
| - this.connectionOptions, |
43 |
| - (connectionError: Error, connection: Connection) => { |
44 |
| - if (connectionError) { |
45 |
| - Logger.error( |
46 |
| - "Connection error in RabbitMQService: " + |
47 |
| - JSON.stringify(connectionError.message), |
48 |
| - "RabbitMQService", |
49 |
| - ); |
50 |
| - return; |
51 |
| - } |
52 |
| - this.connection = connection; |
| 77 | + parseConfig(): void { |
| 78 | + const connectionOptions: Record<string, string | number> = {}; |
| 79 | + RabbitMQService.configKeys.forEach( |
| 80 | + (configKey) => |
| 81 | + (connectionOptions[configKey] = this.getValueFromConfig(configKey)), |
| 82 | + ); |
| 83 | + connectionOptions.protocol = "amqp"; |
| 84 | + this.connectionOptions = connectionOptions as typeof this.connectionOptions; |
| 85 | + } |
53 | 86 |
|
54 |
| - this.connection.createChannel( |
55 |
| - (channelError: Error, channel: Channel) => { |
56 |
| - if (channelError) { |
57 |
| - Logger.error( |
58 |
| - "Channel error in RabbitMQService: " + |
59 |
| - JSON.stringify(channelError.message), |
60 |
| - "RabbitMQService", |
61 |
| - ); |
62 |
| - return; |
63 |
| - } |
64 |
| - this.channel = channel; |
65 |
| - }, |
66 |
| - ); |
67 |
| - }, |
68 |
| - ); |
69 |
| - } |
| 87 | + async onModuleInit(): Promise<void> { |
| 88 | + Logger.log("Initializing RabbitMQService.", "RabbitMQService"); |
| 89 | + this.parseConfig(); |
| 90 | + await this.connect(); |
70 | 91 | }
|
71 | 92 |
|
72 |
| - private async connect(queue: string, exchange: string, key: string) { |
73 |
| - try { |
74 |
| - await this.channel.assertQueue(queue, { durable: true }); |
75 |
| - await this.channel.assertExchange(exchange, "topic", { |
76 |
| - durable: true, |
77 |
| - }); |
78 |
| - await this.channel.bindQueue(queue, exchange, key); |
79 |
| - } catch (error) { |
80 |
| - throw new Error( |
81 |
| - `Could not connect to RabbitMQ queue ${queue} with exchange ${exchange} and key ${key}.`, |
82 |
| - { cause: error }, |
83 |
| - ); |
84 |
| - } |
| 93 | + @OnError("log") |
| 94 | + private async connect(): Promise<void> { |
| 95 | + this._error = "Cannot connect to RabbitMQ: "; |
| 96 | + this.connection = await amqplibConnect(this.connectionOptions); |
| 97 | + this._error = "Channel error in RabbitMQService: "; |
| 98 | + this.channel = await this.connection.createChannel(); |
85 | 99 | }
|
86 | 100 |
|
87 |
| - async sendMessage(queue: string, exchange: string, key: string, message: string) { |
88 |
| - try { |
89 |
| - await this.connect(queue, exchange, key); |
90 |
| - await this.channel.publish(exchange, key, Buffer.from(message), { |
91 |
| - persistent: true, |
92 |
| - }); |
93 |
| - } catch (error) { |
94 |
| - throw new Error(`Could not send message to RabbitMQ queue ${queue}.`, { |
95 |
| - cause: error, |
96 |
| - }); |
97 |
| - } |
| 101 | + @OnError() |
| 102 | + private async bindQueue(queue: string, exchange: string, key: string) { |
| 103 | + this._error = `Could not connect to RabbitMQ queue ${queue} with exchange ${exchange} and key ${key}.`; |
| 104 | + await this.channel.assertQueue(queue, { durable: true }); |
| 105 | + await this.channel.assertExchange(exchange, "topic", { |
| 106 | + durable: true, |
| 107 | + }); |
| 108 | + await this.channel.bindQueue(queue, exchange, key); |
| 109 | + } |
| 110 | + |
| 111 | + @OnError() |
| 112 | + async sendMessage( |
| 113 | + queue: string, |
| 114 | + exchange: string, |
| 115 | + key: string, |
| 116 | + message: string, |
| 117 | + ) { |
| 118 | + this._error = `Could not send message to RabbitMQ queue ${queue}.`; |
| 119 | + await this.bindQueue(queue, exchange, key); |
| 120 | + this.channel.publish(exchange, key, Buffer.from(message), { |
| 121 | + persistent: true, |
| 122 | + }); |
98 | 123 | }
|
99 | 124 |
|
100 | 125 | async close(): Promise<void> {
|
101 | 126 | if (this.channel) {
|
102 |
| - await this.channel.close(() => { |
103 |
| - Logger.log("RabbitMQ channel closed.", "RabbitMQService"); |
104 |
| - }); |
| 127 | + await this.channel.close(); |
| 128 | + Logger.log("RabbitMQ channel closed.", "RabbitMQService"); |
105 | 129 | }
|
106 | 130 | if (this.connection) {
|
107 |
| - await this.connection.close(() => { |
108 |
| - Logger.log("RabbitMQ connection closed.", "RabbitMQService"); |
109 |
| - }); |
| 131 | + await this.connection.close(); |
| 132 | + Logger.log("RabbitMQ connection closed.", "RabbitMQService"); |
110 | 133 | }
|
111 | 134 | }
|
112 | 135 |
|
|
0 commit comments