mywn9
mywn9

Reputation: 107

Unable to parse JSON response from SQS in Lambda node.js function

I am trying to get some data via Webhook into lambda function using API Gateway and SQS. This Webhook contains a JSON payload, and HTTP headers that provide context. Since there is no way to get these webhook HTTP headers from API Gateway to SQS using "Action=SendMessage" in Mapping template (correct me if my assumption is wrong...I have tried http headers in method request and integration request), I have included the headers from webhook in the API Gateway mapping template as follows:

Action=SendMessage&MessageGroupId=$input.params('MessageGroupId')&
MessageBody={
"Header1":"$input.params('Header1 key')",
"body":"$input.json('$')"
}

My code in Lambda function is as follows:

'use strict';

exports.handler = async function(event, context) {

if (event.Records) {
    event.Records.forEach(record => {
      var rec = JSON.parse(JSON.stringify(record.body));
      console.log("Record body: " + rec);

      console.log("Header1: " + rec.Header1);
      
  });
  }  
  return {};
  
};

The value of 'rec' in CloudWatch log is rather quite long but here is the simplified version:

Record body: {
"Header1":" OYqmDnuUpDs8oF1RwoBnJywBY6c1I4qLklU=",
"body":"{"id":820982911946154508,"email":"[email protected]","closed_at":null,"created_at":"2020-11-30T20:25:43-05:00","updated_at":"2020-11-30T20:25:43-05:00","number":234,"note":null,"token":"123456abcd","gateway":null,"test":true,"total_price":"7.00","subtotal_price":"-3.00"
}

My question - how can I read the values of Header1 and body? I have tried rec.Header1, rec[0].Header1 and rec["Header1"] etc. and I get "Undefined" in all the cases. Thanks.

Upvotes: 1

Views: 2319

Answers (1)

LaurensUP
LaurensUP

Reputation: 21

The body is already stringified. You need to simply call JSON.parse(record.body) to parse the string to valid JSON. Note that this could throw an error.

Upvotes: 2

Related Questions