尝试将数据从 lex 插入到 DynamoDB。但出现错误

问题描述 投票:0回答:1

朋友 在下面的代码中出现错误。请帮忙。 错误:

{
  "errorType": "TypeError",
  "errorMessage": "Cannot read properties of undefined (reading 'slots')",
  "trace": [
    "TypeError: Cannot read properties of undefined (reading 'slots')",
    "    at userRegistration (/var/task/index.js:23:38)",
    "    at Runtime.exports.handler (/var/task/index.js:56:9)",
    "    at Runtime.handleOnceNonStreaming (file:///var/runtime/index.mjs:1173:29)"
  ]
}

代码:

    console.log('Loading event');
    var AWS = require('aws-sdk');
    var dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
    var tableName = "GenAITestDemo";

    // Close dialog with the customer, reporting fulfillmentState of Failed or Fulfilled
    function close(sessionAttributes, fulfillmentState, message) {
    return {
        sessionAttributes,
        dialogAction: {
            type: 'Close',
            fulfillmentState,
            message,
        },
    };
}

    function userRegistration(intent, callback) {

    let userInfo = {};

    // store every slot we received as part of registration
    Object.keys(intent.currentIntent.slots).forEach((item) => {
        console.log(item)
        userInfo[item] = {"S": intent.currentIntent.slots[item]};
    });

    // store a registration date
    userInfo.registration_date = {"S": new Date().getTime().toString() };
    userInfo.UserEmail = {"S": intent.UserEmail};
    
    dynamodb.putItem({
        "TableName": tableName,
        "Item" : userInfo
    }, function(err, data) {
        if (err) {
            console.log('Failure storing user info');
            console.log(err);
            callback(close(intent.sessionAttributes, 'Fulfilled',
            {'contentType': 'PlainText', 'content': "I am sorry, but something went wrong saving your Registration Info. Please try again."}));
        } else {
            console.log("Successfully Stored UserInfo");
            callback(close(intent.sessionAttributes, 'Fulfilled',
            {'contentType': 'PlainText', 'content': "Thank you for registering for our service."}));
        }
    });
}

// --------------- Main handler -----------------------
 
// Route the incoming request based on intent.
// The JSON body of the request is provided in the event slot.
    exports.handler = (event, context, callback) => {
    console.log(event);
    try {
        userRegistration(event,
            (response) => {
                callback(null, response);
            });
    } catch (err) {
        callback(err);
    }
};
node.js amazon-dynamodb lex
1个回答
0
投票

您的问题与 DynamoDB 无关,您尝试在不存在的对象中读取

slots
时出现异常。重点关注这一段代码:

Object.keys(intent.currentIntent.slots).forEach((item) => {
        console.log(item)
        userInfo[item] = {"S": intent.currentIntent.slots[item]};
    });

确保

intent.currentIntent.slots
存在并且
intent.currentIntent.slots[item]
也是有效路径。打印出这些值并在日志中检查它们。

© www.soinside.com 2019 - 2024. All rights reserved.