【问题标题】:AWS Lambda to query DynamoDB table returns NULLAWS Lambda 查询 DynamoDB 表返回 NULL
【发布时间】:2020-07-09 05:33:24
【问题描述】:

我是 AWS 的初学者,现在卡住了。我能够创建一个网页来收集联系我们的详细信息并将其写入名为“WebUser-ContactUS”的 DynamoDB 表。我创建了另一个(参考)表,其中我指定表“WebUser-ContactUS”现在由员工 GiselleS 处理。我希望通过这个 lambda 函数获取表的名称,并根据员工的 id 动态显示其内容。

这是我当前从引用表中获取记录的代码,它返回 NULL(虽然成功):

// Load the AWS SDK for JS
var AWS = require("aws-sdk");

// Set a region to interact with (make sure it's the same as the region of your table)
AWS.config.update({region: 'us-west-2'});

// Create the Service interface for DynamoDB
var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

// Create the Document Client interface for DynamoDB
var ddbDocClient = new AWS.DynamoDB.DocumentClient();

// Get a single item with the getItem operation
function GetTasks(tblname, itemname, employee) {
        var params = {
        TableName: "map_Assignments",
        KeyConditionExpression: "#TaskID = :TaskIDValue",
        ExpressionAttributeNames: {
            "#TaskID":"TaskID",
        },
        ExpressionAttributeValues: {
            ":TaskIDValue": itemname,
        },
        Limit: 1
    };
        ddbDocClient.query(params, function(err, data) {
          if (err) { console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2)); return 'error'}
          else { console.log("Query succeeded:", JSON.stringify(data, null, 2)); return data}
        });
}

exports.handler = function (event, context, callback) {
    console.log('Received event:', event);
    // Setting up variables:
    const AssignmentID = event.AssignmentID;
    const Action = event.Action;
    // Calculating variables:
    const Tasks = GetTasks("map_Assignments", event.TaskID, event.EmployeeNetworkID);
    
    const response = {
        statusCode: 200,
        body: Tasks
    };
    callback(null, JSON.stringify(Tasks));
};

这是日志: 回复: 空

请求 ID: "cb1a88f6-6496-49a5-8ee5-aab3400d49e5"

功能日志: 开始请求 ID:cb1a88f6-6496-49a5-8ee5-aab3400d49e5 版本:$LATEST 2020-07-08T19:50:30.694Z cb1a88f6-6496-49a5-8ee5-aab3400d49e5 INFO 收到事件:{ EmployeeNetworkID:'GiselleS',TaskID:1,操作:'Get'} 2020-07-08T19:50:31.394Z cb1a88f6-6496-49a5-8ee5-aab3400d49e5 INFO 查询成功:{ “项目”: [ { "TaskName": "客户服务", “任务ID”:1, "TaskDescription": "处理通过联系我们表单提交的网络用户消息", "EmployeeNetworkID": "GiselleS", "CreateDt": "2020-07-04", “TableWithTaskDetails”:“WebUser-ContactUS” } ], “计数”:1, “扫描计数”:1 } END RequestId...


当我尝试在最后一行切换到下面的情况下获取表名的值时,函数失败:

callback(null, JSON.stringify(Tasks[0].TableWithTaskDetails));

这是错误信息:

回应: { "errorType": "TypeError", "errorMessage": "无法读取未定义的属性 '0'", “痕迹”: [ "TypeError: 无法读取未定义的属性 '0'", "在 Runtime.exports.handler (/var/task/index.js:44:40)", “在 Runtime.handleOnce (/var/runtime/Runtime.js:66:25)” ] }

请求 ID: "f7934e30-21ff-430b-a583-c991af3ef9e2"

功能日志: 开始请求 ID:f7934e30-21ff-430b-a583-c991af3ef9e2 版本:$LATEST 2020-07-08T19:42:19.688Z f7934e30-21ff-430b-a583-c991af3ef9e2 INFO 收到事件:{ EmployeeNetworkID:'GiselleS',TaskID:1,操作:'Get'} 2020-07-08T19:42:20.195Z f7934e30-21ff-430b-a583-c991af3ef9e2 错误调用错误 {"errorType":"TypeError","errorMessage":"Cannot read property '0' of undefined","stack": ["TypeError: 无法读取未定义的属性 '0'"," 在 Runtime.exports.handler (/var/task/index.js:44:40)"," 在 Runtime.handleOnce (/var/runtime/Runtime. js:66:25)"]} END RequestId...

请帮助我继续前进并获取字段 TableWithTaskDetails "WebUser-ContactUS" 的值作为此函数的结果。

【问题讨论】:

    标签: javascript lambda null amazon-dynamodb


    【解决方案1】:

    GetTasks 函数不返回任何内容。 data对象只在ddbDocClient.query函数的回调函数中返回。

    用回调解决它:为GetTasksfunction 提供回调:

    function GetTasks(tblname, itemname, employee, cb) {
      var params = {
        TableName: 'map_Assignments',
        KeyConditionExpression: '#TaskID = :TaskIDValue',
        ExpressionAttributeNames: {
          '#TaskID': 'TaskID',
        },
        ExpressionAttributeValues: {
          ':TaskIDValue': itemname,
        },
        Limit: 1,
      };
      ddbDocClient.query(params, function (err, data) {
        if (err) {
          console.error(
            'Unable to read item. Error JSON:',
            JSON.stringify(err, null, 2)
          );
          cb(err, null);
        } else {
          console.log('Query succeeded:', JSON.stringify(data, null, 2));
          cb(null, data);
        }
      });
    }
    

    在 lambda 函数中:

    exports.handler = function (event, context, callback) {
      console.log('Received event:', event);
      // Setting up variables:
      const AssignmentID = event.AssignmentID;
      const Action = event.Action;
      const response = {
        statusCode: 200,
        body: Tasks,
      };
    
      // Calculating variables:
      GetTasks('map_Assignments', event.TaskID, event.EmployeeNetworkID, function (
        err,
        data
      ) {
        if (data)
          callback(null, JSON.stringify(data.Items[0].TableWithTaskDetails));
        else callback(err, null);
      });
    };
    
    

    【讨论】:

    • 根据您的建议替换,但再次失败并显示以下消息:响应:{“errorType”:“TypeError”,“errorMessage”:“无法读取未定义的属性'Items'”,“trace”: [“TypeError:无法读取未定义的属性‘项目’”、“在 Runtime.exports.handler (/var/task/index.js:44:41)”、“在 Runtime.handleOnce (/var/runtime/Runtime. js:66:25)" ] }
    • 好的,我明白了。 GetTasks 函数不返回任何内容。 data 对象只在query 函数的回调函数中返回。我会更新答案。
    • 太棒了!请点击投票按钮下方的复选框接受它作为答案。
    猜你喜欢
    • 2019-11-26
    • 2020-10-06
    • 2019-05-03
    • 2017-02-17
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多