I am writing an API gateway which must accept HTTP requests from the front-end, collect the requested information using RabbitMQ messaging and finally return this information on the HTTP response. My approach is to use the RPC mechanism as described in the RabbitMQ example
. However it is not clear to me if this can work. My HTTP framework calls the
function shown below and expects the result in a promise. However if I structure the function similar to the RabbitMQ example, the message returned by the back-end service is nested inside the callback function supplied to channel.consume(). Thus the result is not available in the final then clause. Is there a way to do this?
getAccount(accountId) {
let self = {
conn: null,
ch: null,
replyToQ: null,
correlationId: uuidV4()
};
return amqp.connect(url)
.then((conn) => {
self.conn = conn;
return conn.createChannel();
})
.then((ch) => {
return ch.assertQueue('', { exclusive: true });
})
.then((result) => {
self.replyToQ = result.queue;
// Set up a listener on the replyToQ
return self.ch.consume(
self.replyToQ,
(msg) => {
if (msg.properties.correlationId === self.correlationId) {
// The result is available in the callback here, not in the final then clause!!!
const account = JSON.parse(msg.content.toString());
self.conn.close();
}
},
{ noAck: true });
})
.then(() => {
return Promise.all([
self.ch.assertQueue(ACCOUNT_GET_QUEUE, { durable: true }),
self.ch.sendToQueue(
ACCOUNT_GET_QUEUE,
new Buffer(JSON.stringify({accountId})),
{ contentType: 'text/plain', correlationId: self.correlationId, replyTo: self.replyToQ })
]);
});
}