I'm writing a code that will connect API Gateway and DynamoDB. and they are as below.
Put Data
var body = JSON.parse(event.body);
console.log(body.phone)
var table = "userAddresses";
var params = {
TableName: table,
Item: {
"phone": body.phone,
"apartmentNumber": body.apartmentNumber,
"buildingNumber": body.buildingNumber,
"state": body.state,
"zip": body.zip
}
}
docClient.put(params, function (err, data) {
if (err) {
console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
var res = {
"statusCode": 200,
"headers": {},
"body": JSON.stringify(data)
};
context.succeed(res);
}
});
Get Data
var body = JSON.parse(event.body);
console.log(body.phone)
var table = "userAddresses";
var params = {
TableName: table,
Item: {
"phone": body.phone
}
}
docClient.get(params, function (err, data) {
if (err) {
console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
var res = {
"statusCode": 200,
"headers": {},
"body": JSON.stringify(data)
};
context.succeed(res);
}
});
And in my API Gateway I've created resources and methods, and pointed them to corresponding functions, but now I'm thinking to create a common lambda function with 2 methods like function putData() and function getData() and point them to appropriate methods instead of pointing to different Lambda functions. I tried to get the HTTP method by following https://kennbrodhagen.net/2015/12/02/how-to-access-http-headers-using-aws-api-gateway-and-lambda/ and then write as if(method==="GET"){...} else {...}, but unfortunately, I was unable to get the method name itself.
Please help me on how can I do this.
Thanks