Last active
September 13, 2022 07:24
-
-
Save Sleavely/f0a607bb60ca9e1eda429413e1c762b8 to your computer and use it in GitHub Desktop.
A brief example of how interacting with SQS works in a Lambda environment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const SQS = require('aws-sdk/clients/sqs') | |
const { | |
AWS_REGION = 'eu-west-1', | |
MY_QUEUE_URL, | |
} = process.env | |
const sqs = new SQS({ region: AWS_REGION }) | |
/** | |
* @param {any} message | |
* @param {number} delaySeconds Seconds between 0 and 900 | |
* @returns | |
*/ | |
exports.queue = async (message, delaySeconds = 0) => { | |
if (delaySeconds > 15 * 60) throw new Error('SQS can only delay messages up to 15 minutes.') | |
const sqsParams = { | |
QueueUrl: MY_QUEUE_URL, | |
MessageBody: JSON.stringify(message), | |
} | |
if (delaySeconds) sqsParams.DelaySeconds = delaySeconds | |
return sqs.sendMessage(sqsParams).promise() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { queue } = require('./sqsClient.js') | |
const myMainFunction = async () => { | |
// Something we want to send through the queue | |
const superImportantMessage = { | |
hello: 'world' | |
} | |
await queue(superImportantMessage) | |
} | |
myMainFunction() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Parse incoming SQS messages process them | |
*/ | |
exports.handler = async (event) => { | |
for (const record of event.Records) { | |
const superImportantMessage = JSON.parse(record.body) | |
// do something with the message | |
console.log(`This is a message for the ${superImportantMessage.hello}`) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment