DynamoDB,Lambda函数/自定义模块超时

时间:2018-08-09 12:46:55

标签: node.js callback aws-lambda amazon-dynamodb

我有以下两个JS文件。我的问题是,当我调用Calls.js时,后者调用Archive.js将日志归档到DynamoDB中,请求超时。 我已经尝试了很多东西,读了很多东西,在本地/ AWS环境中尝试了很多运气。我想念什么?

Link1Link2Link3Link4Link5

Archive.js

module.exports.archive = archive;
...
function archive(input, callback){
  AWS.config.update({
    region: "eu-west-1",
    endpoint: "http://localhost:8000"
  });
  var documentClient = new AWS.DynamoDB.DocumentClient({
    httpOptions: {
      agent: new https.Agent({
        rejectUnauthorized: true,
        secureProtocol: "TLSv1_method",
        ciphers: "ALL"
      })
    }
  });
...
  var paramsPUT = {
    TableName: "Logging",
    Item: {
      HashKey: dbID,
      archiveEntry: archiveEntry
    }
  };
...
documentClient.put(paramsPUT, function(err, data) {

    if (err) console.log(err);
    if (data) console.log(data);
...
callback(data);
  });


}

Calls.js

exports.handler(event, context, callback)   => {
    const archive = require("./..path..").archive;
    ...
    context.callbackWaitsForEmptyEventLoop = false;
    ...
        archive(input, callback);
    ...
    }

1 个答案:

答案 0 :(得分:1)

我无法使用您的代码重现超时条件。您的代码正在与http://localhost:8000处的AWS终端节点进行通信,因此我假设您已经在本地运行DynamoDB,不是吗?无法运行本地DynamoDB将导致超时。

话虽如此,我强烈建议您重构代码,以使用Promise和NodeJS 8提供的新async / await而不是传递Lambda回调。

这是修改后的代码。

const AWS = require("aws-sdk");

async function archive(input) {

    return new Promise( (resolve, reject) => {
        AWS.config.update({
            region: "eu-west-1",
            endpoint: 'http://localhost:8000'        
        });

        //use client specific AWS configuration instead of the global one
        const documentClient = new AWS.DynamoDB.DocumentClient();

        var paramsPUT = {
            TableName: "Logging",
            Item: {
                HashKey: "123",
                archiveEntry: input
            }
        };

        documentClient.put(paramsPUT, function (err, data) {

            if (err) {
                console.log("ERROR " + err);
                reject(err);
            }

            console.log("Returned from DDB " + JSON.stringify(data, null,2));
            resolve(data);
        });

    });
}

exports.handler = async (event, context, callback) => {
    const result = await archive("abc");
    callback(result);
}

// stuffs to test locally 

callback = function (data) {
    console.log("callback called with " + JSON.stringify(data,null,2));
}

event = context = {}

exports.handler(event, context, callback);