-
Notifications
You must be signed in to change notification settings - Fork 16
/
dso.ts
74 lines (64 loc) · 1.33 KB
/
dso.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
import { Client, ClientConfig } from "../deps.ts";
import { BaseModel } from "./model.ts";
import { sync } from "./sync.ts";
import { Transaction } from "./transaction.ts";
/** @ignore */
let _client: Client;
/** @ignore */
let _models: BaseModel[] = [];
/**
* Global dso instance
*/
export const dso = {
/**
* set true will show exucte/query sql
*/
showQueryLog: false,
/**
* Sync model to database table
* @param force set true, will drop table before create table
*/
async sync(force: boolean = false): Promise<void> {
for (const model of _models) {
await sync(_client, model, force);
}
},
/**
* Database client
*/
get client(): Client {
return _client;
},
/**
* all models
*/
get models() {
return _models;
},
/**
* add model
* @param model
*/
define<T extends BaseModel>(ModelClass: { new (): T }): T {
const model = new ModelClass();
_models.push(model);
return model;
},
transaction: Transaction.transaction,
/**
* connect to database
* @param config client config
*/
async connect(config: ClientConfig | Client) {
if (config instanceof Client) {
_client = config;
} else {
_client = new Client();
await _client.connect(config);
}
return _client;
},
close(): void {
_client.close();
},
};