consume a sqs topic in typescript

Here is an example code to consume a SQS topic in TypeScript:

  1. First, install the AWS SDK for JavaScript:
npm install aws-sdk --save
27 chars
2 lines
  1. Add the following import statements to your TypeScript file:
index.ts
import * as AWS from 'aws-sdk';
const sqs = new AWS.SQS({ region: 'REGION' });
79 chars
3 lines
  1. Configure your AWS credentials:
index.ts
AWS.config.update({
   accessKeyId: 'ACCESS_KEY_ID',
   secretAccessKey: 'SECRET_ACCESS_KEY',
   region: 'REGION'
});
118 chars
6 lines
  1. Define a callback function that will be called when a message is received:
index.ts
const messageProcessor = (message: AWS.SQS.Types.Message) => {
   console.log(`Received message: ${message.Body}`);
   // Add your message processing logic here
};
164 chars
5 lines
  1. Define the parameters for consuming messages from the SQS queue:
index.ts
const params: AWS.SQS.Types.ReceiveMessageRequest = {
   QueueUrl: 'QUEUE_URL',
   MaxNumberOfMessages: 10,
   WaitTimeSeconds: 10
};
134 chars
6 lines
  1. Call the sqs.receiveMessage() method with the defined queue parameters and the callback function:
index.ts
sqs.receiveMessage(params, (err: any, data: AWS.SQS.Types.ReceiveMessageResult) => {
      if (err) {
         console.error(err);
      } else if (data.Messages) {
         console.log(`Processing ${data.Messages.length} messages`);
         data.Messages.forEach(messageProcessor);
      } else {
         console.log('No messages to process');
      }
});
359 chars
11 lines

This code will continuously poll the SQS queue for messages, and when a message is received your callback function will be called to process the message. The WaitTimeSeconds parameter determines how long the SQS queue will wait before returning an empty response, allowing your code to efficiently consume messages.

gistlibby LogSnag