-
Notifications
You must be signed in to change notification settings - Fork 0
/
repo-context.ts
69 lines (59 loc) · 2.05 KB
/
repo-context.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 { Configuration, EntityManager, MikroORM, Options } from '@mikro-orm/core';
import { MySqlDriver } from '@mikro-orm/mysql';
import { SqliteDriver } from '@mikro-orm/sqlite';
import { TsMorphMetadataProvider } from '@mikro-orm/reflection';
import Repository from '@/service/Repository';
import Member from '@/domain/model/Member';
import RepoTemplate from './impl/RepoTemplate';
import Authority from '@/domain/model/Authority';
const { DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE, DB_PORT, DB_TYPE } = process.env;
const isPool = process.env.NODE_ENV === 'production' || process.env.NODE_ENV !== 'test';
export const basicOption: Options<MySqlDriver & SqliteDriver> = {
// debug: true,
metadataProvider: TsMorphMetadataProvider,
host: DB_HOST,
user: DB_USERNAME,
password: DB_PASSWORD,
dbName: DB_DATABASE,
port: isNaN(Number(DB_PORT)) ? 3306 : Number(DB_PORT),
entities: ['./dist/domain/model'],
entitiesTs: ['./src/domain/model'],
migrations: {
path: `dist/migrations/${DB_TYPE}`,
pathTs: `src/migrations/${DB_TYPE}`,
},
type: DB_TYPE as keyof typeof Configuration.PLATFORMS,
};
if (isPool) {
basicOption.pool = {
max: 10,
min: 5,
idleTimeoutMillis: 10000,
acquireTimeoutMillis: 30000,
};
}
let orm: MikroORM<MySqlDriver | SqliteDriver>;
const initOrm = async () => {
if (!orm) {
console.debug('INIT ORM');
orm = DB_TYPE === 'sqlite'
? await MikroORM.init<SqliteDriver>(basicOption)
: await MikroORM.init<MySqlDriver>(basicOption);
}
return orm;
};
type RepoContext = {
memRepo: Repository<Member, number>;
authRepo: Repository<Authority, number>;
};
const ctx = {} as RepoContext;
/**
* to Use context function Orm must be called and orm instance must be not null
* initOrm is called in index.ts to boot service or global-suite.ts to test
*/
export const repoContext = (em?: EntityManager) => {
// ctx.memRepo = ctx.memRepo ?? new MemberRepoImpl(em ?? orm.em);
ctx.memRepo = ctx.memRepo ?? new RepoTemplate<Member, number>(em ?? orm.em, Member);
return ctx;
};
export default initOrm;