-
-
Notifications
You must be signed in to change notification settings - Fork 496
/
MikroORM.ts
63 lines (50 loc) · 1.75 KB
/
MikroORM.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
import { EntityManager } from './EntityManager';
import { IDatabaseDriver } from './drivers';
import { MetadataDiscovery } from './metadata';
import { Configuration, Logger, Options } from './utils';
import { EntityMetadata } from './decorators';
export class MikroORM {
em: EntityManager;
readonly config: Configuration;
private metadata: Record<string, EntityMetadata>;
private readonly driver: IDatabaseDriver;
private readonly logger: Logger;
static async init(options: Options): Promise<MikroORM> {
const orm = new MikroORM(options);
const driver = await orm.connect();
orm.em = new EntityManager(orm.config, driver);
try {
const storage = new MetadataDiscovery(orm.em, orm.config, orm.logger);
orm.metadata = await storage.discover();
return orm;
} catch (e) {
await orm.close(true);
throw e;
}
}
constructor(options: Options | Configuration) {
if (options instanceof Configuration) {
this.config = options;
} else {
this.config = new Configuration(options);
}
this.driver = this.config.getDriver();
this.logger = this.config.getLogger();
}
async connect(): Promise<IDatabaseDriver> {
await this.driver.getConnection().connect();
const clientUrl = this.config.getClientUrl(true);
const dbName = this.config.get('dbName');
this.logger.info(`MikroORM: successfully connected to database ${dbName}${clientUrl ? ' on ' + clientUrl : ''}`);
return this.driver;
}
async isConnected(): Promise<boolean> {
return this.driver.getConnection().isConnected();
}
async close(force = false): Promise<void> {
return this.driver.getConnection().close(force);
}
getMetadata(): Record<string, EntityMetadata> {
return this.metadata;
}
}