从NodeJS AWS Lambda函数查询MySQL数据库

时间:2017-03-04 03:08:35

标签: mysql node.js amazon-web-services aws-lambda

我在使用AWS Lambda函数查询MySQL数据库(从AWS远程托管)时遇到问题。

这是我的代码,除了Lambda函数的其余部分所需的部分(正在为Alexa技能调用):

  var mysql = require('mysql');
  var connection = mysql.createConnection({
        host     : '<myserver>',
        user     : '<myusername>',
        password : '<mypw>',
        database : '<mydatabase>'
  });
  connection.connect(function(err){
        if(!err) {
              console.log("Database is connected ... nn");
        }
        else {
              console.log("Error connecting database ... nn");
        }
  });

  connection.query("INSERT INTO Users (user_id) VALUES ('TESTNAME')");
  connection.end();

当我从命令提示符运行节点时,这很好用:

node index.js

我正在使用通过npm在index.js目录下安装的“mysql”模块并将其压缩并上传到我的Lambda函数。

同样,这可以在我的开发机器上运行,但在测试我的Lambda函数时没有给出任何指示,因为它根本不会影响我的数据库。

我的问题扩展到了Alexa和Lambda,就像正确使用mysql Node.JS模块一样。

这是我当前的Lambda代码,当然这里的问题仍然是我的测试值 - &gt;名为“TESTNAME”的用户名不会添加到我的MySQL数据库中。

我将查询放入连接回调中,正如第一条评论所暗示的那样,我正在使用我的新代码而不是更新上面的旧代码,只是为了记录我认为代码应该如何转换为我的代码。 Alexa的Lambda功能:

更新的代码:

var mysql = require('mysql');
var connection = mysql.createConnection({
      host     : '<myserver>',
      user     : '<myusername>',
      password : '<mypw>',
      database : '<mydatabase>'
});
exports.handler = (event, context) => {
    try {

        if (event.session.new) {
            // New Session
            console.log("NEW SESSION");
        }


        switch (event.request.type) {

            case "LaunchRequest":
                // Launch Request
                console.log(`LAUNCH REQUEST`);
                context.succeed(
                    generateResponse({},
                        buildSpeechletResponse("Welcome to an Alexa Skill, this is running on a deployed lamda function", true)
                    )
                );
                break;

            case "IntentRequest":
                // Intent Request
                console.log(`Intent Request`);
                console.log('Then run MySQL code:');
                connection.connect(function(err) {
                    console.log('Inside connection.connect() callback');
                    if (!err) {
                        console.log("Database is connected ... ");
                        connection.query("INSERT INTO Users (user_id) VALUES ('TESTNAME')",
                            function(err, result) {
                                console.log("Inside connection.query() callback")
                                if (!err) {
                                    console.log("Query Successful! Ending Connectection.");
                                    connection.end();
                                } else {
                                    console.log("Query error!");
                                }
                            });
                    } else {
                        console.log("Error connecting database ..." + err.message);
                    }
                });
                context.succeed(
                    generateResponse({},
                        buildSpeechletResponse("Welcome to the incredible intelligent MySQLable Alexa!", true)
                    )
                );

                break;

            case "SessionEndedRequest":
                // Session Ended Request
                console.log(`SESSION ENDED REQUEST`);
                break;

            default:
                context.fail(`INVALID REQUEST TYPE: ${event.request.type}`);

        }

    } catch (error) {
        context.fail(`Exceptiodn: ${error}`)
    }

};

//Helpers
buildSpeechletResponse = (outputText, shouldEndSession) => {

    return {
        outputSpeech: {
            type: "PlainText",
            text: outputText
        },
        shouldEndSession: shouldEndSession
    };
};

generateResponse = (sessionAttributes, speechletResponse) => {
    return {
        version: "1.0",
        sessionAttributes: sessionAttributes,
        response: speechletResponse
    };
};

我的控制台输出:

START RequestId: 5d4d17a7-0272-11e7-951c-b3d6944457e1 Version: $LATEST
2017-03-06T13:39:47.561Z    5d4d17a7-0272-11e7-951c-b3d6944457e1    Intent Request
2017-03-06T13:39:47.562Z    5d4d17a7-0272-11e7-951c-b3d6944457e1    Then run MySQL code:
END RequestId: 5d4d17a7-0272-11e7-951c-b3d6944457e1
REPORT RequestId: 5d4d17a7-0272-11e7-951c-b3d6944457e1  Duration: 82.48 ms  Billed Duration: 100 ms     Memory Size: 128 MB Max Memory Used: 14 MB  

1 个答案:

答案 0 :(得分:4)

问题是我需要将context.succeed放在回调中。非常感谢sqlbot,因为他对回调的讨论让我研究了事情实际上已经结束了他们的执行。

显然,在使用AWS Lambda时,如果“回调”被调用之前“上下文”结束,则不会得到回调。所以即使我把所有的回调都放在了这样的地方:connect - &gt;查询 - &gt;结束,来自connect的链的第一个回调永远不会被调用,因为“context.succeed”之后被调用,结束了执行。

这是我现在的代码(现在正在进行正确的查询):

var mysql = require('mysql');
var connection = mysql.createConnection({
    ...
});

exports.handler = (event, context) => {
    try {

        if (event.session.new) {
            // New Session
            console.log("NEW SESSION");
        }


        switch (event.request.type) {

            case "LaunchRequest":
                // Launch Request
                console.log(`LAUNCH REQUEST`);
                context.succeed(
                    generateResponse({},
                        buildSpeechletResponse("Welcome to an Alexa Skill, this is running on a deployed lamda function", true)
                    )
                );
                break;

            case "IntentRequest":
                // Intent Request
                console.log(`Intent Request`);
                console.log('Then run MySQL code:');
                connection.connect(function(err) {
                    console.log('Inside connection.connect() callback');
                    if (!err) {
                        console.log("Database is connected ... ");
                        connection.query("INSERT INTO Users (user_id) VALUES ('TESTNAME')",
                            function(err, result) {
                                console.log("Inside connection.query() callback")
                                if (!err) {
                                    console.log("Query Successful! Ending Connection.");
                                    connection.end();
                                } else {
                                    console.log("Query error!");
                                }
                            });
                    } else {
                        console.log("Error connecting database ..." + err.message);
                    }
                    context.succeed(
                        generateResponse({},
                            buildSpeechletResponse("Welcome to the incredible intelligent MySQLable Alexa!", true)
                        )
                    );
                });

                break;

            case "SessionEndedRequest":
                // Session Ended Request
                console.log(`SESSION ENDED REQUEST`);
                break;

            default:
                context.fail(`INVALID REQUEST TYPE: ${event.request.type}`);

        }

    } catch (error) {
        context.fail(`Exceptiodn: ${error}`)
    }

};

//Helpers
buildSpeechletResponse = (outputText, shouldEndSession) => {

    return {
        outputSpeech: {
            type: "PlainText",
            text: outputText
        },
        shouldEndSession: shouldEndSession
    };
};

generateResponse = (sessionAttributes, speechletResponse) => {
    return {
        version: "1.0",
        sessionAttributes: sessionAttributes,
        response: speechletResponse
    };
};