How to use queues in your serverless app

Link to chapter — https://serverless-stack.com/examples/how-to-use-queues-in-your-serverless-app.html

Is there any way to retrieve MessageBody in the consumer lambda function?

The example code doesn’t work as is (as of the time of this post), nor does it show how to process a consumed event from the queue. After downloading the example, here are the modifications that I made.

First, queue.QueueName will not work in the lambda. The example sets the environment variable queueUrl to queue.queueName and then uses it in lambda.ts. However, if you run it as-is, you’ll get an error that you’re referencing an unknown endpoint. What you should do is use the sqs object to get the QueueUrl. So you go from this:

  await sqs.sendMessage({ QueueUrl: process.env.queueUrl });

to this

  const queueUrl = await sqs.getQueueUrl({ QueueName: process.env.queueUrl }).promise();
  await sqs.sendMessage({ QueueUrl: queueUrl.QueueUrl });

Second, the example does not show what arguments are passed to the consumer. You can track this down by looking for other SQS consumer examples. For typescript, you’ll change the consumer to this:

export const main: SQSHandler = async(event) => {
  console.log('Event received!');

  event.Records.forEach((record) => {
    console.log(JSON.stringify(record));
  });
}

Notice that we’ve typed the function to the type of handler the AWS SDK expects. It will help you understand what types of parameters and their properties exist.

1 Like

Oh that’s not good. We’ll have it checked out!

I had the same problem and @villecoder solution worked like a charm. Nonetheless, I’ve found another way to fix the issue by replacing queueName with queueUrl:

// MyStack.ts

const api = new Api(stack, "Api", {
  defaults: {
    function: {
      // Pass in the queue to our API
      environment: {
        queueUrl: queue.queueUrl, // Replaced queueName with queueUrl
      },
    },
  },
  routes: {
    "POST /": "functions/lambda.handler",
  },
});

Original error:

ERROR UnknownEndpoint: Inaccessible host: `my-queue' at port `undefined'. This service may not be available in the `us-east-1' region.