Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all messages from AWS SQS in NodeJS

I have the following function that gets a message from aws SQS, the problem is I get one at a time and I wish to get all of them, because I need to check the ID for each message:

function getSQSMessages() {

    const params = {
        QueueUrl: 'some url',
    };

    sqs.receiveMessage(params, (err, data) => {
        if(err) {
            console.log(err, err.stack)
            return(err);
        }
        return data.Messages;
    });

};

function sendMessagesBack() {

    return new Promise((resolve, reject) => {
        if(Array.isArray(getSQSMessages())) {
            resolve(getSQSMessages());
        } else {
            reject(getSQSMessages());
        };
    });

};

The function sendMessagesBack() is used in another async/await function. I am not sure how to get all of the messages, as I was looking on how to get them, people mention loops but I could not figure how to implement it in my case. I assume I have to put sqs.receiveMessage() in a loop, but then I get confused on what do I need to check and when to stop the loop so I can get the ID of each message?

If anyone has any tips, please share. Thank you.

like image 830
squeekyDave Avatar asked Jan 02 '23 00:01

squeekyDave


2 Answers

I suggest you to use the Promise api, and it will give you the possibility to use async/await syntax right away.

const { Messages } = await sqs.receiveMessage(params).promise();
// Messages will contain all your needed info
await sqs.sendMessage(params).promise();

In this way, you will not need to wrap the callback API with Promises.

like image 129
Alexandru Olaru Avatar answered Jan 03 '23 13:01

Alexandru Olaru


SQS doesn't return more than 10 messages in the response. To get all the available messages, you need to call the getSQSMessages function recursively. If you return a promise from getSQSMessages, you can do something like this.

getSQSMessages()
.then(data => {
  if(!data.Messages || data.Messages.length === 0){
      // no messages are available. return
  }
  // continue processing for each message or push the messages into array and call 
 //getSQSMessages function again. 
});
like image 29
Swarup Bam Avatar answered Jan 03 '23 13:01

Swarup Bam