Reputation: 51
I have created an api, when called, triggers the lambda function, written in nodejs, to take the json(array of objects) and insert the data into dynamodb. For each object in the array, the function creates a PutRequest object and when finished calls the batchWriteItem function. When I test in the aws console everything works fine but when I try in postman I get a 500 error. I know that the event is different when coming from postman vs the console and you are supposed to reference "event.body" if you want to access the json however when I do that I get an error with event.body.ForEach: "Cannot read property 'forEach' of undefined" in the console and a 500 error in postman. Below is the code that works in the console
var dynamo = new AWS.DynamoDB({region: 'us-east-1',});
exports.handler = (event, context, callback) => {
const done = (err, res) => callback(null, {
statusCode: err ? '400' : '200',
body: err ? err.message : res,
});
var params = {
RequestItems: {
"Lead": []
}
}
event.forEach(x => {
params.RequestItems.Lead.push({
PutRequest: {
Item: {
"Address": {S: x.Address},
"City": {S: x.City},
"State": {S: x.State},
"Zipcode": {S: x.Zipcode},
"Owner_First_Name": {S: x.Owner_First_Name},
"Owner_Last_Name": {S: x.Owner_Last_Name}
}
}
})
})
dynamo.batchWriteItem(params, done);
};
Upvotes: 3
Views: 1945
Reputation: 8593
When the lambda receive the json body from api gateway, it will be passed as a json string.
To convert the json string to json, You need to parse the event.body.
const body = JSON.parse(event.body)
Then you can do body.forEach
Hope this helps
Upvotes: 1