如何使用mysql连接和node.js池中的单身devise模式

我正在使用node-mysql作为orm。 ( https://github.com/mysqljs/mysql )

我正在使用MySQL和Node.JS创build一个REST API。 之前我使用MongoDB做了同样的事情。 它工作正常。 github.com/chanakaDe/Mint-REST。 现在我想用MySQL来做同样的事情。 我做了大部分的工作,并有一个小问题。 有很多类,我需要集中使用mysql连接。 作为单身devise模式。

这是我的新回购。 https://github.com/chanakaDe/MintRestSQL 。 而且我会显示我想要使用这些模式的位置。 在这里我有数据库文件。 我创build了一个新的连接池。 github.com/chanakaDe/MintRestSQL/blob/master/app/util/database.js。

现在我想在我的控制器类中使用这个连接/池。 因为我无法在每个控制器类中创build连接。 没有? 这是我现在的两个控制器。 github.com/chanakaDe/MintRestSQL/blob/master/app/routes/report.js github.com/chanakaDe/MintRestSQL/blob/master/app/routes/api.js

请给我一个更好的方法来做到这一点。 我是node-mysql的新手。 但是在Node.JS环境中使用MySQL甚至在生产级系统中也是一个很好的方法。 所以我想用这些标准来制作一个好的API。 有没有什么办法使用单例模式或类似的东西,集中连接,并在所有的控制器中使用它?

它将花费一些时间来检查我的文件和理解代码。 但请检查并给我一个解决scheme。 我试了很多东西,但没有工作:(

欢迎您提出回购并进行更新

尝试改变database.js

var mysql = require('mysql'); mysql.createPool({ host : 'localhost', user : 'root', password : 'chanaka', database : 'shared_adult' }).connect(); module.exports = mysql; 

提供一个替代任何人到达这里(如我)需要注入依赖(即凭据)。 下面是将产生一个运行时可configuration单例​​的方法:

 var mysql = require('mysql'), db; module.exports = { init: function(conf){ if(!db){ db = mysql.createPool({ host: conf.host, user: conf.root, password: conf.password, database: conf.database }); } }, get: function() { if(!db) { throw new Error('The db pool has not been initialized, call init({}) prior to get().'); } return db; } }; //initialize where you access your config (which should theoretically only be one place) var mysqlDb = require('db'); //path to above db module mysqlDb.init({ host: 'host', user: 'user', password: 'password', database: 'database' }); //use in your modules var mysqlDb = require('db'), //path to above db module db = mysqlDb.get();