无法使用带有 S3 触发器的 Lambda 函数写入 DynamoDB

Failing to write to DynamoDB using Lambda function with an S3 trigger

我正在尝试编写一个 lambda 函数,每当将新图像写入 S3 存储桶时都会触发该函数。触发器已使用正确的 S3 存储桶设置,所以我知道这不是问题所在。

lambda 函数本身具有角色 s3:GetObject 和 dynamodb.*(对于 DynamoDB 写入应该具有完全访问权限)。

这里的目标是简单地写入我已经创建的名为 'art' 的 table 并插入一个我试图在 [= 中获取的主键值 (imageTitle) 11=]。然后我想为该键分配一个属性,该属性是该图像的 url,我存储在 var url.

这只是一个简单的练习,我正试图记下来,以便我可以继续进行更复杂的数据库写入。但截至目前,我没有将任何内容写入 art table,即使我将新对象添加到触发触发器的 S3 存储桶中也是如此。是否有可能未部署 lambda 函数?我是直接在Lambda Console的内联编辑器里写的,然后保存的。

代码如下:

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'});
const s3 = new AWS.S3();

exports.handler = async (event, context, callback) => {
    //var sourceBucket = event.Records[0].s3.bucket.name;
    var sourceKey = event.Records[0].s3.object.key;
    var imageName = sourceKey.stringify;

    //generate imageURL
    var url = "https://s3.amazonaws.com/myapp-20181030214040-deployment/public/" + imageName;

    var params = {
        TableName : 'art',
        Item: {
            imageTitle: imageName,
            imageURL: url
        }
    };
    docClient.put(params, function(err, data) {
       if (err) console.log(err);
       else console.log(data);
    });
};

这里的问题是您使用的是异步 lambda 但 return 没有任何可等待的东西。这意味着您的 lambda 在发送 docClient.put 操作之前终止。

对于 async 处理程序,您需要等待和 return,例如,您可以将此代码段更改为:

const data = await docClient.put(params).promise();
return data;

或者您可以使用 callback 方法(注意处理程序的签名 不再 包含 async):

exports.handler = (event, context, callback) => {
  // ... the rest of the code as was ...
  docClient.put(params, function(err, data) {
    if (err) {
      console.log(err);
      callback(err); // return 'lambda invoke failed because of the error' - will cause s3 to retry three times.
    } else {
      console.log(data);
      callback(null, data); // return 'nothing failed'; n.b. the s3 trigger ignores whatever you return.
    }
  });
};