I\'m trying to write a Lambda function using Node.js which connects to my RDS database. The database is working and accessible from my Elastic Beanstalk environment. When I
I have also faced similar timeout scenario. Issue was not doing connection.end() after connection.connect(). Connection.end() should be done before callback.
Working Code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'host_name',
user : 'root',
password : 'password'
});
module.exports.handler = (event, context, callback) => {
// **Connection to database**
connection.connect(function(err) {
if (err) {
console.error('Database connection failed: ' + err.stack);
return;
}
console.log('Connected to database.');
});
// **Hit DB Query**
connection.query("Query", function(err, rows, fields) {
console.log(rows);
});
//**Close Connection**
connection.end(); ***// Missing this section will result in timeout***
//**Send API Response**
callback(null, {
statusCode: '200',
body: "Success",
headers: {
'Content-Type': 'application/json',
},
});
};