Node.js and Lambda

I’ve been working on the API Gateway/Lambda code for ConMagick now for a bit.  Everything was working quite well, then all of the sudden I was getting connection issues.  After searching the web I found some solutions, but the error still arose.  After trial and error I finally found the fix and wanted to document it for anyone else that runs into this.

Node.js (lambda) and MySql work well, but unless you build the code 100% clean it will not work properly and you will get drops after your connections to the db server are maxed out.  The code I present below is how to properly implement a query through lambda (node.js).

This code takes in two variables, one from the URL and the other from the head.  (I won’t cover the API Gateway portion on here, that’s for another day).  The entire key to this process is to make sure that your connection is properly setup and then closed.  That last part being the key, if you don’t close the connection it will keep them open and will eventually cause max connection issues with MySQL.

var mysql = require('mysql');
var env = process.env;
const fs = require('fs');

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

    // Get values from the API Gateway
    var itemx = event.params.path.itemx;
    var itemz = event.params.header.itemz;
    
    // Open connection - using environment variables
    var connection  = mysql.createConnection({
        host                 : env.dbhost,
        user                 : env.dbuser,
        password             : env.dbpass,
        database             : env.dbdatabase,
        ssl                 : 'Amazon RDS'
    });
    
    // Read in SQL from file and replace with provided data
    var sql = fs.readFileSync('sqlfile.sql').toString();            
    sql = sql.replace('{{itemx}}', itemx);
    sql = sql.replace('{{itemz}}', itemz);
        
    // Run query on sql
    connection.query(sql, function (error, results) {
        if(error){
            callback(400,'Bad request');
        }else{
            if(results.length >= 1){
                callback(null, {"data": results});
            } else {
                callback(null, {"Valid": false});
            }
        }        
    });
    
    // Close connection
    connection.end(function(err) {
      console.log(err);
    });
}
Advertisements