/
dataSourceManager.ts
75 lines (63 loc) · 1.6 KB
/
dataSourceManager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import {
Config,
Init,
Logger,
Provide,
Scope,
Inject,
ScopeEnum,
listModule,
DataSourceManager,
ILogger,
} from '@midwayjs/core';
import { Sequelize } from 'sequelize-typescript';
@Provide()
@Scope(ScopeEnum.Singleton)
export class SequelizeDataSourceManager extends DataSourceManager<Sequelize> {
@Config('sequelize')
sequelizeConfig;
@Logger('coreLogger')
coreLogger: ILogger;
@Inject()
baseDir: string;
@Init()
async init() {
await this.initDataSource(this.sequelizeConfig, this.baseDir);
}
getName(): string {
return 'sequelize';
}
protected async createDataSource(
config: any,
dataSourceName: string
): Promise<Sequelize> {
const client = new Sequelize(config);
const entities = config['entities'];
if (entities && entities.length > 0) {
client.addModels(entities);
}
// 兼容老写法,但是这里可能有问题,会添加到所有的数据源之中
const listEntities = listModule('sequelize:core');
client.addModels(listEntities);
await client.authenticate();
if (config.sync) {
await client.sync(config.syncOptions);
}
this.coreLogger.info('[midway:sequelize] connecting and start');
return client;
}
protected async checkConnected(dataSource: Sequelize): Promise<boolean> {
try {
await dataSource.authenticate();
return true;
} catch (err) {
this.coreLogger.error(err);
return false;
}
}
protected async destroyDataSource(dataSource: Sequelize) {
if (await this.checkConnected(dataSource)) {
await dataSource.close();
}
}
}