Skip to content

Instantly share code, notes, and snippets.

@Sleavely
Last active September 13, 2022 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sleavely/f0a607bb60ca9e1eda429413e1c762b8 to your computer and use it in GitHub Desktop.
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
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()
}
const { queue } = require('./sqsClient.js')
const myMainFunction = async () => {
// Something we want to send through the queue
const superImportantMessage = {
hello: 'world'
}
await queue(superImportantMessage)
}
myMainFunction()
/**
* 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