9

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);
 })
};
4
  • How are you invoking the Lambda function? Via API gateway? Or directly via the AWS SDK? Commented Aug 17, 2016 at 13:05
  • Please add the output of line console.log('Row Details:', JSON.stringify(res)); Commented Aug 17, 2016 at 15:29
  • Invoking via the API Gateway. Commented Aug 17, 2016 at 15:35
  • Results from console.log('Row Details:') Row Details: [{"applicant_id":"WQFV7CWXA39E9TXT"}] Commented Aug 17, 2016 at 15:36

2 Answers 2

4

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();
};
Sign up to request clarification or add additional context in comments.

7 Comments

Hi @john-siu, Unfortunately that doesn't work as expected... I tried that earlier :-) What it sends back is the following with the brackets before and after... not exactly JSON :-( [ { "applicant_id":"WQFV7CWXA39E9TXT" } ]
If I return the applicant_data JSON variable outside of the callback function it returns the data as I would expect without the brackets.
@Josh It is JSON, but wrapped in an array. The data is in first item of the array.
@Josh Try without JSON.stringify in callback, it is not required. I updated my answer. docs.aws.amazon.com/lambda/latest/dg/…
Thanks for the assist here... I tried it without the stringify and I'm still getting just a { } :-(
|
3
exports.handler = async (event) => {
    let jsonResponse = {"hello":"world"}
    const response = {
        statusCode: 200,
        body: JSON.stringify(jsonResponse),
    };
    return response;
};

2 Comments

Is it possible to return the JSON data as an object instead of a string?
@Crashalot this would be interpreted as an object by most clients and servers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.