2

How to use mysql connection with serverless framework.connection should be available in my component functions without creating mysql connection each time in component function

Tried like this

var mysql  = require('mysql');

module.exports.respond = function(event, cb) {

   var pool      =    mysql.createPool({
        connectionLimit : 100,
        host     : 'hostname',
        user     : 'username',
        password : 'password',
        database : 'databasename',
        debug    :  false
    });
    var message='';
    pool.getConnection(function(err,connection){
        if(err) {
            message='Could not connect to database';
        } else {
            message="Database is connected";
        }
        var response = {
            message: message
        };
        return cb(null, response);
    });


};

but above code will be only available for current function,want to make common thing for mysql connection in serverless framework,can not find proper document about how to use mysql in serverless framework

5 Answers 5

1

I am writing answer of my own question

make database.js file in component/lib folder

code of database.js

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'hostname',
    user     : 'username',
    password : 'password',
    database : 'databasename'
});

connection.connect();
module.exports = connection;

created object like this in component/lib/index.js file

var connection = require("../lib/database.js");

Can use connection variable to write mysql query like this in component/lib/index.js

module.exports.respond = function(event, cb) {

    var query="SELECT * from table_name";

    connection.query(query,function(err,rows) {

    })
};
Sign up to request clarification or add additional context in comments.

2 Comments

Will this open a new connection to the DB each time a Serverless-function is called? Won't this flood the DB?
Thanks for the answer..i have an issue while adding the file as shown var connection = require("../lib/database.js"); I have to replace it with var connection = require("./lib/database.js");
0

I believe you have a Component created in your Serverless Framework based project that contains multiple lambda functions. And now you want to write the MySQL connection code such that this code block is available for re-use in all your lambda functions of that component.

If this is the ask, then Serverless does provide a "lib" folder inside your Component directory, which you can utilize to write common code logic to be re-used. Since you have a NodeJS-based runtime for your component, there should be an "index.js" file inside your Component folder -

your_serverless_project_directory/component_name/lib/index.js

The first thing you want to do is to add the MySQL connection code logic to a function/method in index.js.

Serverless should have already included for you this entire lib/ folder in all your lambda function's handler.js code like this -

var lib = require('../../lib');

Therefore, the next/final thing you want to do is re-use your connection function/method (in all the lambda functions belonging inside your Component) like this -

module.exports.handler = function(event, context) {
  lib.mySQLConnection();
};

Hope this helps, let me know how it goes.

1 Comment

your answer is also correct,but please write code of mySQLConnection function and update your answer,i will tick your answer as correct
0

To build off of Normal Goswami's answer:

You've specified the database here in the connection. My lambdas each need different databases, so in the connection code just leave off the database:

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'hostname',
    user     : 'username',
    password : 'password'
    // no database here
});

connection.connect();
module.exports = connection;

And then use an oddly named function to change the database in each lambda function:

connection.changeUser({database: database}, function(err) {
    if (err) { throw err; }
});

connection.query(sql, function(err, rows, fields) {
    // etc
}

You could also look into using a database connection pool.

Comments

0

you have to make connection out of function, as we are doing it with mongodb we are making mongodb connection out side of Lambda Function.

my code snippet from https://github.com/malikasinger1/serverles-practice/tree/master/mongodb-connection:

var mongoose = require("mongoose");
var dbURI = 'mongodb://localhost/mydatabase';

mongoose.connect(dbURI);
mongoose.connection.on('connected', function () {//connected
    console.log("Mongoose is connected");
    // process.exit(1);
});

module.exports.signup = (event, context, cb) => {

    //doing signup here
}

in your cace it will be something like this most probably:

var mysql  = require('mysql');

//make connection here
var pool   = mysql.createPool({
    ...
});

pool.getConnection(function(err,connection){
    ...
});

module.exports.respond = function(event, cb) {     
    //use connection here
};

Comments

0

I am assuming you are using serverless framework on AWS.

Although you can create a connection and assign it to a frozen variable, it's not guaranteed that your lambda won't create a new connection. Here is why: The best way so far (in my personal opinion) is to create a separate lambda function for db related operations and invoke this function through other lambdas. Here is the flow:

client -> registerUserLambda -> dbLambda -> DATABASE

However, the thing about lambdas is that when there are too many requests, there will be new containers created to handle other requests. That is, new connections will be created. Therefore the concept of connection pools does not work well for now on serverless lambdas.

Comments

Your Answer

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