Search code examples
c#amazon-web-services.net-coreaws-lambdamessage-queue

Mapping issue between AWS SQS and its linked Lambda


Background

I have a function with this signature:

public string Function(MyCommand cmd, ILambdaContext context)

Where MyCommand is:

public class MyCommand 
{
    public string Url { get; set; } = default!;
    public string Email { get; set; } = default!;
}

If I test my lambda on the AWS UI with this body:

{
    'Url': 'https://www.google.com/',
    'Email': '[email protected]'
}

I get the result I want. I have logging in place, on the cloudwatch log, for my lambda I see the following as expected:

Received json: {'Url': 'https://www.google.com/', 'Email': '[email protected]'}

The issue

I have also an SQS queue set up with a trigger on it for my Lambda. If I add the same JSON message to that queue I get the following log output:

Received json: {'Url': null, 'Email': null}

So it looks like my lambda is correctly triggered, because it hits my log code, but the values arrive empty.

What could be the cause of this?


Solution

  • To Process SQS messages within a Lambda function, you need to accept the SQSEvent data type. Though you sent only the MyCommand payload from SQS, when it reaches the lambda function, the message is transformed into SQSEvent

    public string Function(SQSEvent sqsEvent, ILambdaContext context)
    {
        return sqsEvent.Records.First().Body;
    }
    

    p.s. To access SQSEvent in the lambda function, you need to install the following NuGet package: Amazon.Lambda.SQSEvents