Skip to content

Instantly share code, notes, and snippets.

@Sangrene
Last active April 19, 2021 19:26
Show Gist options
  • Save Sangrene/72897a3359092bccdf2b0e818262818a to your computer and use it in GitHub Desktop.
Save Sangrene/72897a3359092bccdf2b0e818262818a to your computer and use it in GitHub Desktop.
const handleCommand = async ({
channel,
from,
func,
to,
}: {
from: string;
to: string;
func: (args: any) => any;
channel: amqp.Channel;
}) => {
await channel.assertQueue(from, { durable: true });
channel.consume(
from,
async (msg) => {
channel.ack(msg);
const payload = JSON.parse(msg.content.toString());
try {
const result = await func(payload);
channel.sendToQueue(to, Buffer.from(JSON.stringify(result)), {
correlationId: msg.properties.correlationId,
persistent: true,
});
} catch (e) {
channel.sendToQueue(to, Buffer.from(JSON.stringify({ error: { name: e.name, message: e.message } })), {
correlationId: msg.properties.correlationId,
persistent: true,
});
}
},
{ noAck: false },
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment