1 | 'use strict';
|
2 |
|
3 | const path = require('path');
|
4 | const Sequelize = require('sequelize');
|
5 | const MODELS = Symbol('loadedModels');
|
6 | const chalk = require('chalk');
|
7 |
|
8 | Sequelize.prototype.log = function() {
|
9 | if (this.options.logging === false) { return; }
|
10 | const args = Array.prototype.slice.call(arguments);
|
11 | const sql = args[0].replace(/Executed \(.+?\):\s{0,1}/, '');
|
12 | this.options.logging.info('[model]', chalk.magenta(sql), `(${args[1]}ms)`);
|
13 | };
|
14 |
|
15 | module.exports = app => {
|
16 | const defaultConfig = {
|
17 | logging: app.logger,
|
18 | host: 'localhost',
|
19 | port: 3306,
|
20 | username: 'root',
|
21 | benchmark: true,
|
22 | define: {
|
23 | freezeTableName: false,
|
24 | underscored: true,
|
25 | },
|
26 | };
|
27 | const config = Object.assign(defaultConfig, app.config.sequelize);
|
28 |
|
29 | app.Sequelize = Sequelize;
|
30 |
|
31 | const sequelize = new Sequelize(config.database, config.username, config.password, config);
|
32 |
|
33 |
|
34 | Object.defineProperty(app, 'model', {
|
35 | value: sequelize,
|
36 | writable: false,
|
37 | configurable: false,
|
38 | });
|
39 |
|
40 | loadModel(app);
|
41 |
|
42 | app.beforeStart(function* () {
|
43 | yield app.model.authenticate();
|
44 | });
|
45 | };
|
46 |
|
47 | function loadModel(app) {
|
48 | const modelDir = path.join(app.baseDir, 'app/model');
|
49 | app.loader.loadToApp(modelDir, MODELS, {
|
50 | inject: app,
|
51 | caseStyle: 'upper',
|
52 | ignore: 'index.js',
|
53 | });
|
54 |
|
55 | for (const name of Object.keys(app[MODELS])) {
|
56 | const instance = app[MODELS][name];
|
57 |
|
58 | if (!(instance instanceof app.Sequelize.Model)) {
|
59 | continue;
|
60 | }
|
61 | app.model[name] = instance;
|
62 | }
|
63 |
|
64 | for (const name of Object.keys(app.model)) {
|
65 | const instance = app.model[name];
|
66 |
|
67 | if ('associate' in instance) {
|
68 | instance.associate();
|
69 | }
|
70 | }
|
71 | }
|