Giter VIP home page Giter VIP logo

express-myconnection's Introduction

express-myconnection

Connect/Express middleware provides a consistent API for MySQL connections during request/response life cycle. It supports three different strategies of managing db connections: single for a singleton connection on an app instance level, pool based connections, and a new connection per each request. It’s also capable of auto closing/releasing connections if configured either with pool or request. It uses node-mysql as a MySQL driver.

Strategies

  • single - creates single database connection for an application instance. Connection is never closed. In case of disconnection it will try to reconnect again as described in node-mysql docs.
  • pool - creates pool of connections on an app instance level, and serves a single connection from pool per request. The connections is auto released to the pool at the response end.
  • request - creates new connection per each request, and automatically closes it at the response end.

Usage

Configuration is straightforward and you use it as any other middleware. First param it accepts is a node-mysql module, second is a db options hash passed to node-mysql module when connection or pool are created. The third is string defining strategy type.

// app.js
...
var mysql = require('mysql'), // node-mysql module
    myConnection = require('express-myconnection'), // express-myconnection module
    dbOptions = {
      host: 'localhost',
      user: 'dbuser',
      password: 'password',
      port: 3306,
      database: 'mydb'
    };
  
app.use(myConnection(mysql, dbOptions, 'single'));
...

express-myconnection extends request object with getConection(callback) function, this way connection instance can be accessed anywhere in routers during request/response life cycle:

// myroute.js
...
module.exports = function(req, res, next) {
    ...
    req.getConnection(function(err, connection) {
      if (err) return next(err);
      
      connection.query('SELECT 1 AS RESULT', [], function(err, results) {
        if (err) return next(err);
        
        results[0].RESULT;
        // -> 1
        
        res.send(200);
      });
      
    });
    ...
}
...

release connection use req.releaseConnection to manual release a connection // myroute.js ... module.exports = function(req, res, next) { ... req.getConnection(function(err, connection) { if (err) return next(err); connection.query('SELECT 1 AS RESULT', [], function(err, results) { connection = null; req.releaseConnection(); //manual to release a connection if (err) return next(err); results[0].RESULT; // -> 1 requestUrl(url, function(err, data) { if (err) return next(err); req.getConnection(function(err, connection) { //get a connection again connection.query('SELECT 2 AS RESULT', [], function(err, results) { res.send(200); }); }); }) });

  });
  ...
}
...

express-myconnection's People

Contributors

bessarabov avatar lix059 avatar outring avatar pwalczyszyn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

express-myconnection's Issues

support for multiple data sources connections?

if we have transactional database and datamart/reporting db can this support having multiple pools available in some way?

first I guess can a given controller/service/router getting a request use getConnection with some qualifier stating which datasource to use?

could it support getting multiple

If client connections drops then the mysql connection is leaked.

I am implementing long polling in express and my clients can timeout and drop the connection.

In this case the connection is leaked using request strategy. I've solved in my long polling code with:

    req.on('close', function(err) {
        req.getConnection(function(err, connection) {
            connection.end();
        });
    });

req.getConnection is not a function

Hi
i am trying to connect mysql, but it is showing me req.getConnection is not a function
Bellow is the code snipet which i have used.
In app.js
var mysql = require('mysql'), connection = require('express-myconnection'), dbOptions = { host: 'localhost', user: 'root', password: '', port: 3306, database: 'nodejs' }; app.use(connection(mysql, dbOptions, 'request'));
In Customers.js
exports.list = function(req, res, next) { req.getConnection(function(err, connection) { if (err) return next(err); connection.query('SELECT * FROM customer', function(err, rows) { if (err) console.log("Error Selecting : %s ", err); res.render('customers', { page_title: "Customers - Node.js", data: rows }); }); }); };

Can you please check what is have done wrong. I am pretty new in nodejs, so may be i am missing something.

If you want to check my complete package, please follow bellow URL, i have push all code in my git repository
https://github.com/chiraggmodi/nodeCrud

connection pool

Connection pool does not work with mysql, when the wait_timeout in mysql the server disconnects. This causes an error to be thrown. Express connection does not reacquire connection. I can find no comments or solutions in any forum on this.

Connection leak when the response is terminated unexpectedly

Node HTTP API defines two events to finish the response: finish and close. When res.end() is called node triggers the finish event, but if the request terminates unexpectedly (i.e.: the client reloads the page before the response is sent) close is triggered instead.

Proxying res.end() does not take into account the close event and it causes a connection leak. The strategy should be changed to listen for both finish and close events.

Problem with 'pool'

var config = {
    db: {
        host: 'localhost',
        user: process.env.DB_USER || 'root',
        password: process.env.DB_PWORD ||  '',
        port: process.env.DB_PORT || 3306,
        database: process.env.DB_NAME || 'xxx',
        multipleStatements: true
    }
}
app.use(myConnection(mysql, config.db, 'pool'));

Gives me the following error:

ReferenceError: pool is not defined
    at IncomingMessage.req.getConnection (/Users/scottvanlooy/Development/Node/fcnode/node_modules/express-myconnection/lib/express-myconnection.js:86:21)
    at getContent (/Users/scottvanlooy/Development/Node/fcnode/routes/index.js:36:7)
    at exports.index (/Users/scottvanlooy/Development/Node/fcnode/routes/index.js:55:2)
    at callbacks (/Users/scottvanlooy/Development/Node/fcnode/node_modules/express/lib/router/index.js:164:37)
    at param (/Users/scottvanlooy/Development/Node/fcnode/node_modules/express/lib/router/index.js:138:11)
    at pass (/Users/scottvanlooy/Development/Node/fcnode/node_modules/express/lib/router/index.js:145:5)
    at Router._dispatch (/Users/scottvanlooy/Development/Node/fcnode/node_modules/express/lib/router/index.js:173:5)
    at Object.router (/Users/scottvanlooy/Development/Node/fcnode/node_modules/express/lib/router/index.js:33:10)
    at next (/Users/scottvanlooy/Development/Node/fcnode/node_modules/express/node_modules/connect/lib/proto.js:193:15)
    at Object.loc [as handle] (/Users/scottvanlooy/Development/Node/fcnode/node_modules/loc/lib/i18n.js:129:3)

Not sure why, any ideas?

express-myconnection with passport.js

Wonder how one would create a LocalStrategy (that autenticates users againsts a user table in a database) using express-myconnection?

There is no req object in this case.

Connection in custom function

How i can use this in my custom function πŸ‘Ž
function dbcheck() {
getConnection(function (err, connection) {
connection.query('SELECT *FROM users ', function (err, results) {
if (err) return next(err);
return results;
});
});
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.