Skip to content

Instantly share code, notes, and snippets.

@ragokan
Created June 15, 2022 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ragokan/23a6fc6089b4473beaff00503372eecd to your computer and use it in GitHub Desktop.
Save ragokan/23a6fc6089b4473beaff00503372eecd to your computer and use it in GitHub Desktop.
RabbitMQ Nest Client
import amqp, { Message, Channel } from "amqplib/callback_api";
const handleMessage = (message: Message, channel: Channel) => {
// Parse message
const content = JSON.parse(message.content.toString()) as IncomingMessage;
// Get properties
const { replyTo, correlationId } = message.properties;
// Reply to message 5 times
for (let index = 0; index < 5; index++) {
const response: OutgoingMessage = {
id: content.id,
// Dispose the listener if it is the last message
isDisposed: index === 4,
response: `Hello ${content.data} ${index}`,
};
// Send response to queue
channel.sendToQueue(replyTo, Buffer.from(JSON.stringify(response)), {
correlationId,
});
}
};
// Connect to RabbitMQ
amqp.connect("amqp://127.0.0.1", (err, connection) => {
throwErrorIfExists(err);
console.log("Connected!");
// Create a channel
connection.createChannel((err, channel) => {
throwErrorIfExists(err);
// Give queue a name
const queue = "hello_queue";
// Create a queue
channel.assertQueue(queue, { durable: false });
// Listen for messages
channel.consume(
queue,
(msg) => {
if (msg === null) return;
return handleMessage(msg, channel);
},
{ noAck: true }
);
});
});
const throwErrorIfExists = (error: Error) => {
if (error) {
throw error;
}
};
interface IncomingMessage {
pattern: string;
data: string;
id: string;
}
interface OutgoingMessage {
response: string;
isDisposed: boolean;
id: string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment