I'm new to NodeJS, and JS in general (mostly a PHP and C# guy), so I could really use some help with this function below.
The goal is to receive a JSON payload, connect to MySQL, and then return the results of the query in a JSON response. I've got it connecting to the DB, I can read the JSON data that it receives (event.fieldname) but for some reason it's not sending back the JSON for the applicant_data variable.
Do I just have the variable in the wrong location? When I run the code below I just get back "{}" as the returned data.
Thanks in advance for the help!
NodeJS Code:
exports.handler = function(event, context, callback) {
console.log('Starting:');
console.log("Request received:\n", JSON.stringify(event));
var mysql = require('mysql');
var jsonconnection = mysql.createConnection({
    host: 'servername',
    user: 'username',
    password: 'password',
    database: 'database'
 });
jsonconnection.connect();
console.log('Connected to MySQL:');
jsonconnection.query('SELECT applicant_id FROM customers WHERE applicant_id = \'' + event.applicant_id + '\'',
    function(err,res){
    if(err) throw err;
    console.log('Row Details:', JSON.stringify(res));
        var applicant_data = {
            applicant_id : res.applicant_id
        };
    jsonconnection.end();
    context.succeed(applicant_data);
 })
};
                I am not familiar with AWS, but base on http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html, following code may work.
exports.handler = function (event, context, callback) {
    console.log('Starting:');
    console.log("Request received:\n", JSON.stringify(event));
    var mysql = require('mysql');
    var jsonconnection = mysql.createConnection({
        host: 'servername',
        user: 'username',
        password: 'password',
        database: 'database'
    });
    // Move applicant_data outside of query as it will be needed at the end in callback
    var applicant_data = {};
    jsonconnection.connect();
    console.log('Connected to MySQL:');
    jsonconnection.query('SELECT applicant_id FROM customers WHERE applicant_id = \'' + event.applicant_id + '\'',
        function (err, res) {
            if (err) throw err;
            console.log('Row Details:', JSON.stringify(res));
            applicant_data = {
                // Only use first row of data
                applicant_id: res[0].applicant_id;
            };
        });
    // Move connection end out side of query
    jsonconnection.end();
    // This should return your data, in JSON form
    callback(null, JSON.stringify(applicant_data));
    // I assume this is the correct use for succeed
    context.succeed();
};
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With