1 | 'use strict';
|
2 |
|
3 | const assert = require('assert');
|
4 | const path = require('path');
|
5 | const Sequelize = require('sequelize');
|
6 |
|
7 | module.exports = app => {
|
8 | const config = Object.assign(app.config.sequelize, { logging });
|
9 |
|
10 | assert(config.database, 'config.database is required');
|
11 | assert(config.username, 'config.username is required');
|
12 | assert(config.host, 'config.host is required');
|
13 | assert(config.port, 'config.port is required');
|
14 |
|
15 | const sequelize = new Sequelize(
|
16 | config.database,
|
17 | config.username,
|
18 | config.password,
|
19 | {
|
20 | host: config.host,
|
21 | port: config.port,
|
22 | dialect: config.dialect,
|
23 | logging: config.logging,
|
24 | }
|
25 | );
|
26 |
|
27 | Object.defineProperty(app, 'sequelize', {
|
28 | value: sequelize,
|
29 | writable: false,
|
30 | configurable: false,
|
31 | });
|
32 |
|
33 | loadModel(app);
|
34 |
|
35 | app.beforeStart(function* () {
|
36 | yield app.sequelize.authenticate();
|
37 | app.logger.info('[egg-sequelize] start success');
|
38 | });
|
39 |
|
40 | function logging(str) {
|
41 | app.coreLogger.info(`[egg-sequelize] ${str}`);
|
42 | }
|
43 | };
|
44 |
|
45 | function loadModel(app) {
|
46 | const direcotry = path.join(app.baseDir, 'app/model');
|
47 | app.loader.loadToApp(direcotry, 'model', {
|
48 | inject: app.sequelize,
|
49 | });
|
50 |
|
51 | for (const name of Object.keys(app.model)) {
|
52 | if ('associate' in app.model[name]) {
|
53 | app.model[name].associate(app.model);
|
54 | }
|
55 | }
|
56 | }
|