使用DynamoDb、Lambda、Api网关将多个地图添加到列表中



我正在向Api网关传递一个params,以便使用AWS Lambda Node JS将其保存在DynamoDB中。

Api网关的集成请求是:

#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"
}

AWS Lambda(Node JS(的内容,用于接收参数并将其保存到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);
})

但是Dynamo DB中保存的项目只包含一个调查,即调查两个。应该是2,因为我通过了调查一和调查二的类型和答案。

我的预期结果应该是

{
"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" }
]
}

我建议使用DynamoDb DocumentClient类。

您可以提供相同的参数,但使用本机JS类型。

DocumentClient为您进行编组和解编组,这可能是您的surveyTwo问题的问题。

你的例子会是这样的。

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);
});

最新更新