0
votes

I'm passing a params to Api Gateway to be saved in DynamoDB using AWS Lambda Node JS.

The integration request of Api Gateway is:

#set($inputRoot = $input.path('$'))
{
  "name" : "$inputRoot.name",
  "profileImage": "$inputRoot.profileImage",
  "gender" : "$inputRoot.gender",
  "interests": #foreach ( $item in ["$inputRoot.interests"] ) $item #end,
  "surveyOne": "$inputRoot.surveyOne",
  "surveyOneAnswer": "$inputRoot.surveyOneAnswer",
  "surveyTwo": "$inputRoot.surveyTwo",
  "surveyTwoAnswer": "$inputRoot.surveyTwoAnswer"
}

The content of AWS Lambda (Node JS) to receive the params and save it to DynamoDB:

const params = {
    Item: {
      'uuid': { S: "i_" + uuidv4() }, 
      'name': { S: event.name }, 
      'profileImage': { S: event.profileImage },
      'gender': { S: event.gender },
      'interests': { SS: event.interests },
      'surveys' : {
        L: [
          { 
            M: {
              'type': { S: event.surveyOne },
              'answer': { S: event.surveyOneAnswer },
            },
            M: {
              'type': { S: event.surveyTwo },
              'answer': { S: event.surveyTwoAnswer }
            }
          }
        ]
      }
     }, 
     TableName: 'users'
   };

   dynamodb.putItem(params, (err, data) => {
     if (err) {
      const response = {
        statusCode: 500, 
        headers: {
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({status: false})
      };
      return callback(null, response);  
    } 

    // return status 200 if success
    const response = {
      statusCode: 200, 
      headers: {
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({status: 'A new record has been added'})
    };
    return callback(null, response);

   })

But the saved item in Dynamo DB only contains one survey which is the surveyTwo. It should be 2 because I passed surveyOne and surveyTwo type and answer.

My expected result should be

{
  "name": "John Doe",
  "profileImage": "https://example.com", 
  "gender": "m", 
  "interests": ["Basketball",  "Swimming"],
  "surveys": [
    { "type": "question 1", "answer": "answer to question 1" },
    { "type": "question 2", "answer": "answer to question 2" }
  ]
}
1

1 Answers

1
votes

I would recommend to use the DynamoDb DocumentClient Class.

You can supply the same parameters, but with native JS types.

The DocumentClient does the marshalling and unmarshalling for you, which might be the problem with your surveyTwo issue.

Your example would then look something like this.

var params = {
 TableName : 'users',
 Item: {
     uuid: 'i_' + uuidv4(),
     name: event.name,
     surveys: [
        {type: event.surveyOne, answer: event.surveyOneAnswer},
        {type: event.surveyTwo, answer: event.surveyTwoAnswer}]
     }
};

var documentClient = new AWS.DynamoDB.DocumentClient();

  documentClient.put(params, function(err, data) {
 if (err) console.log(err);
 else console.log(data);
});