我在使用DynamoDB时遇到了一些麻烦。我已经为完整的CRUDL设置了Lambda权限(管理员访问权限,因此没有任何限制)。以下是处理程序,它基于doca https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.NodeJs.03.html
const uuidv4 = require("uuid/v4");
const services = require("./services/services");
var AWS = require("aws-sdk");
AWS.config.update({ region: "eu-west-2" });
var docClient = new AWS.DynamoDB.DocumentClient();
var tableName = "usersTable";
module.exports = {
registerUser: async (event, context) => {
const id = uuidv4();
let body;
if (event.body !== null && event.body !== undefined) {
body = JSON.parse(event.body);
}
const isValid = await services.validateUser(body);
if (isValid) {
var params = {
TableName: tableName,
Item: {
userId: "123abc",
firstName: "finn",
lastName: "murtons",
email: "email@email.com",
password: "secret"
}
};
console.log("Adding a new item...");
console.log(" Adding params", params);
docClient.put(params, function(err, data) {
if (err) {
console.error(
"Unable to add item. Error JSON:",
JSON.stringify(err, null, 2)
);
} else {
console.log("Added item:", JSON.stringify(data, null, 2));
}
});
}
},
... other functions
在此示例中,为了清晰起见,我正在对参数进行硬编码,但显然,我通常会从event.body中获取它们。
当我向此Lambda发出发布请求时,出现502错误。 查看cloudwatch日志,它可以达到:
INFO Adding params { TableName: 'usersTable',
Item:
{ userId: '123abc',
firstName: 'finn',
lastName: 'murtons',
email: 'email@email.com',
password: 'secret' } }
然后就没有更多日志了。忽略isValid函数,它只是检查请求事件主体是否具有必填字段。
有人对我可能会出错的地方有任何想法吗?
答案 0 :(得分:2)
lambda可能在进行DynamoDB调用之前退出。您应该将呼叫设为Promise
并等待:
await docClient.put(params).promise();