event-publishing.ts81 lines, 2.0 KB
| 1 | import { |
| 2 | AUTH_EVENT_EXCHANGE, |
| 3 | AUTH_USER_REGISTERED_ROUTING_KEY, |
| 4 | type AuthUserRegisteredPayload, |
| 5 | } from '@chatapp/common'; |
| 6 | import { connect, type Channel, type ChannelModel } from 'amqplib'; |
| 7 | |
| 8 | import { env } from '@/config/env'; |
| 9 | import { logger } from '@/utils/logger'; |
| 10 | |
| 11 | let connectionRef: ChannelModel | null = null; |
| 12 | let channel: Channel | null = null; |
| 13 | |
| 14 | export const initPublisher = async () => { |
| 15 | if (!env.RABBITMQ_URL) { |
| 16 | logger.warn('RABBITMQ_URL is not defined. Skipping RabbitMQ initialization.'); |
| 17 | return; |
| 18 | } |
| 19 | |
| 20 | if (channel) { |
| 21 | return; |
| 22 | } |
| 23 | |
| 24 | const connection = await connect(env.RABBITMQ_URL); |
| 25 | connectionRef = connection; |
| 26 | channel = await connection.createChannel(); |
| 27 | await channel.assertExchange(AUTH_EVENT_EXCHANGE, 'topic', { durable: true }); |
| 28 | |
| 29 | connection.on('close', () => { |
| 30 | logger.warn('RabbitMQ connection closed'); |
| 31 | channel = null; |
| 32 | connectionRef = null; |
| 33 | }); |
| 34 | connection.on('error', (err) => { |
| 35 | logger.error({ err }, 'RabbitMQ connection error'); |
| 36 | }); |
| 37 | |
| 38 | logger.info('Auth service RabbitMQ publisher initialized'); |
| 39 | }; |
| 40 | |
| 41 | export const publishUserRegistered = (payload: AuthUserRegisteredPayload) => { |
| 42 | if (!channel) { |
| 43 | logger.warn('RabbitMQ channel is not initialized. Cannot publish message.'); |
| 44 | return; |
| 45 | } |
| 46 | |
| 47 | const event = { |
| 48 | type: AUTH_USER_REGISTERED_ROUTING_KEY, |
| 49 | payload, |
| 50 | occuredAt: new Date().toISOString(), |
| 51 | metadata: { version: 1 }, |
| 52 | }; |
| 53 | |
| 54 | const published = channel.publish( |
| 55 | AUTH_EVENT_EXCHANGE, |
| 56 | AUTH_USER_REGISTERED_ROUTING_KEY, |
| 57 | Buffer.from(JSON.stringify(event)), |
| 58 | { contentType: 'application/json', persistent: true }, |
| 59 | ); |
| 60 | |
| 61 | if (!published) { |
| 62 | logger.warn({ event }, 'Failed to publish user registered event'); |
| 63 | } |
| 64 | }; |
| 65 | |
| 66 | export const closePublisher = async () => { |
| 67 | try { |
| 68 | const ch = channel; |
| 69 | if (ch) { |
| 70 | await ch.close(); |
| 71 | channel = null; |
| 72 | } |
| 73 | const conn = connectionRef; |
| 74 | if (conn) { |
| 75 | await conn.close(); |
| 76 | connectionRef = null; |
| 77 | } |
| 78 | } catch (error) { |
| 79 | logger.error({ err: error }, 'Error closing RabbitMQ connection/channel'); |
| 80 | } |
| 81 | }; |