rabbitmq.consumer.ts87 lines, 2.3 KB
| 1 | import { env } from '@/config/env'; |
| 2 | import { userRepository } from '@/repositories/user.repository'; |
| 3 | import { logger } from '@/utils/logger'; |
| 4 | import { |
| 5 | USER_CREATED_ROUTING_KEY, |
| 6 | USER_EVENTS_EXCHANGE, |
| 7 | type UserCreatedEvent, |
| 8 | } from '@chatapp/common'; |
| 9 | |
| 10 | import { |
| 11 | connect, |
| 12 | type Channel, |
| 13 | type ChannelModel, |
| 14 | type ConsumeMessage, |
| 15 | type Replies, |
| 16 | } from 'amqplib'; |
| 17 | |
| 18 | let connection: ChannelModel | null = null; |
| 19 | let channel: Channel | null = null; |
| 20 | let consumerTag: string | null = null; |
| 21 | |
| 22 | const EVENT_QUEUE = 'chat-service.user-events'; |
| 23 | |
| 24 | const closeAmqpConnection = async (conn: ChannelModel) => { |
| 25 | await conn.close(); |
| 26 | }; |
| 27 | |
| 28 | const handleUserCreated = async (event: UserCreatedEvent) => { |
| 29 | await userRepository.upsertUser(event.payload); |
| 30 | }; |
| 31 | |
| 32 | export const startConsumers = async () => { |
| 33 | if (!env.RABBITMQ_URL) { |
| 34 | logger.info('RabbitMQ URL not configured; consumers disabled'); |
| 35 | return; |
| 36 | } |
| 37 | |
| 38 | const conn = await connect(env.RABBITMQ_URL); |
| 39 | connection = conn; |
| 40 | const ch = await conn.createChannel(); |
| 41 | channel = ch; |
| 42 | |
| 43 | await ch.assertExchange(USER_EVENTS_EXCHANGE, 'topic', { durable: true }); |
| 44 | const queue = await ch.assertQueue(EVENT_QUEUE, { durable: true }); |
| 45 | await ch.bindQueue(queue.queue, USER_EVENTS_EXCHANGE, USER_CREATED_ROUTING_KEY); |
| 46 | |
| 47 | const consumeHandler = (message: ConsumeMessage | null) => { |
| 48 | if (!message) { |
| 49 | return; |
| 50 | } |
| 51 | |
| 52 | void (async () => { |
| 53 | const payload = message.content.toString('utf-8'); |
| 54 | const event = JSON.parse(payload) as UserCreatedEvent; |
| 55 | await handleUserCreated(event); |
| 56 | ch.ack(message); |
| 57 | })().catch((error: unknown) => { |
| 58 | logger.error({ err: error }, 'Failed to process event'); |
| 59 | ch.nack(message, false, false); |
| 60 | }); |
| 61 | }; |
| 62 | |
| 63 | const result: Replies.Consume = await ch.consume(queue.queue, consumeHandler); |
| 64 | consumerTag = result.consumerTag; |
| 65 | logger.info('RabbitMQ consumer started'); |
| 66 | }; |
| 67 | |
| 68 | export const stopConsumers = async () => { |
| 69 | try { |
| 70 | const ch = channel; |
| 71 | if (ch && consumerTag) { |
| 72 | await ch.cancel(consumerTag); |
| 73 | consumerTag = null; |
| 74 | } |
| 75 | if (ch) { |
| 76 | await ch.close(); |
| 77 | channel = null; |
| 78 | } |
| 79 | const conn = connection; |
| 80 | if (conn) { |
| 81 | await closeAmqpConnection(conn); |
| 82 | connection = null; |
| 83 | } |
| 84 | } catch (error) { |
| 85 | logger.error({ err: error }, 'Error stopping RabbitMQ consumer'); |
| 86 | } |
| 87 | }; |