database.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. require('mysql');
  2. var fs = require("fs");
  3. var orm = require("orm");
  4. var Promise = require("bluebird");
  5. var path = require("path");
  6. /*
  7. app: 应用程序环境
  8. config: 数据库配置
  9. callback: 回调
  10. */
  11. function initialize(app,callback) {
  12. // 加载配置文件
  13. var config = require('config').get("db_config");
  14. // 从配置中获取数据库配置
  15. var opts = {
  16. protocol : config.get("protocol"),
  17. host : config.get("host"),
  18. database : config.get("database"),
  19. port : config.get("port"),
  20. user : config.get("user"),
  21. password : config.get("password"),
  22. query : {pool: true,debug: true}
  23. };
  24. console.log("数据库连接参数 %s",JSON.stringify(opts));
  25. // 初始化ORM模型
  26. app.use(orm.express(opts, {
  27. define: function (db, models, next) {
  28. app.db = db;
  29. global.database = db;
  30. // 获取映射文件路径
  31. var modelsPath = path.join(process.cwd(),"/models");
  32. // 读取所有模型文件
  33. fs.readdir(modelsPath,function(err, files) {
  34. // 存放所有的加载模型函数
  35. var loadModelAsynFns = new Array();
  36. // console.log("开始加载 ORM 模型层文件 ");
  37. for (var i = 0; i < files.length; i++) {
  38. var modelPath = modelsPath + "/" +files[i];
  39. // console.log("加载模型 %s",modelPath);
  40. loadModelAsynFns[i] = db.loadAsync(modelPath);
  41. }
  42. Promise.all(loadModelAsynFns)
  43. .then(function(){
  44. // console.log("ORM 模型加载完成");
  45. // 挂载模型集合
  46. for(var modelName in db.models){
  47. models[modelName] = db.models[modelName];
  48. }
  49. app.models = models;
  50. callback(null);
  51. next();
  52. })
  53. .catch(function(error){
  54. console.error('加载模块出错 error: ' + err);
  55. callback(error);
  56. next();
  57. });
  58. });
  59. }
  60. }));
  61. }
  62. module.exports.initialize = initialize;
  63. module.exports.getDatabase = function() {
  64. return global.database;
  65. }