-
Notifications
You must be signed in to change notification settings - Fork 1
/
orm.ts
69 lines (56 loc) · 1.76 KB
/
orm.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
import { context, register, typeLoader } from 'egg-aop';
import { getGlobalType } from 'power-di/utils';
export * from 'orm-ts';
function getRepositoryKey(modelType: any) {
return `${getGlobalType(modelType)}@Repository`;
}
function registerRepository(modelType: any, repoType: any) {
register('Context', repoType, getRepositoryKey(modelType))(repoType);
}
export function repository(modelType: any) {
return (target: any) => {
registerRepository(modelType, target);
};
}
//#region 添加MySQL提供程序
import * as co from 'co';
import { getInstance } from 'egg-aop';
import { IProvider, BaseRepository } from 'orm-ts';
let BaseRepositoryType = BaseRepository;
export function setBaseRepository(target: any) {
BaseRepositoryType = target;
}
@context(IProvider)
export class MySQLProvider<T> implements IProvider<T> {
constructor(
protected ctx: any
) {
}
getRepositoryByModelClass(modelType: any): BaseRepository {
if (!modelType) {
throw new Error('No modelType!');
}
const ormConfig = this.ctx.app.config.orm;
const key = getRepositoryKey(modelType);
if (!typeLoader.has(key)) {
class TmpRepository extends BaseRepositoryType {
constructor() {
super(modelType, ormConfig);
}
}
registerRepository(modelType, TmpRepository);
return this.getRepositoryByModelClass(modelType);
}
return getInstance(key, this.ctx.app, this.ctx);
}
private get mysql() {
return this.ctx._transactionConnection || (this.ctx.app as any).mysql;
}
async queryOne(sql: string, params?: any): Promise<T> {
return await co(this.mysql.queryOne(sql, params));
}
async query(sql: string, params?: any): Promise<T[]> {
return await co(this.mysql.query(sql, params));
}
}
//#endregion