|
1 | | -var fs = require('fs'), |
2 | | - path = require('path'), |
3 | | - Sequelize = require('sequelize'), |
4 | | - db = {}; |
5 | | - |
| 1 | +"use strict"; |
| 2 | + |
| 3 | +var fs = require('fs'); |
| 4 | +var path = require('path'); |
| 5 | +var Sequelize = require('sequelize'); |
| 6 | + |
| 7 | +/** |
| 8 | + * Register sequelize as a Hapi plugin |
| 9 | + * @param plugin |
| 10 | + * @param options |
| 11 | + * @param next |
| 12 | + */ |
6 | 13 | exports.register = function(plugin, options, next) { |
7 | 14 |
|
8 | | - // Create db connection |
| 15 | + var db = {}; |
| 16 | + var dir = path.join(process.env.PWD, options.models); |
| 17 | + |
9 | 18 | var sequelize = new Sequelize(options.database, options.user, options.pass, { |
10 | | - dialect: options.dialect || 'mysql', |
| 19 | + dialect: options.dialect || 'mysql', |
11 | 20 | port: options.port || 3306 |
12 | 21 | }); |
13 | 22 |
|
14 | | - // Add all models in directory to db object |
15 | | - fs |
16 | | - .readdirSync(path.resolve(__dirname, '../../models')) |
17 | | - .filter(function(file) { |
18 | | - return (file.indexOf('.') !== 0) && (file !== 'index.js'); |
19 | | - }) |
20 | | - .forEach(function(file) { |
21 | | - var model = sequelize.import(path.join(path.resolve(__dirname, '../../models'), file)); |
| 23 | + fs.readdirSync(dir).filter(function(file) { |
| 24 | + return file.indexOf('.') !== 0; |
| 25 | + }).forEach(function(file) { |
| 26 | + var filePath = path.join(dir, file); |
| 27 | + var model = sequelize.import(filePath); |
22 | 28 | db[model.name] = model; |
23 | 29 | }); |
24 | 30 |
|
25 | | - // Create associations |
26 | | - Object.keys(db).forEach(function (modelName) { |
27 | | - if ('associate' in db[modelName]) { |
28 | | - db[modelName].associate(db) |
| 31 | + Object.keys(db).forEach(function(modelName) { |
| 32 | + if ("associate" in db[modelName]) { |
| 33 | + db[modelName].associate(db); |
29 | 34 | } |
30 | 35 | }); |
31 | 36 |
|
32 | 37 | db.sequelize = sequelize; |
33 | 38 | db.Sequelize = Sequelize; |
34 | 39 |
|
35 | | - plugin.expose('models', db); |
| 40 | + plugin.expose('db', db); |
36 | 41 |
|
37 | 42 | next(); |
38 | 43 | }; |
|
0 commit comments