Skip to content

Commit 1b51edf

Browse files
author
Matija Petrunic
committed
Reuse database connection when using repository outside controller
1 parent f8c0e1e commit 1b51edf

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
"scripts": {
1111
"start:dev": "npx task dev",
1212
"db:migration:new": "yarn run typeorm-ts migration:create -n ",
13-
"db:migration:generate": "yarn run typeorm-ts migration:create -n ",
13+
"db:migration:generate": "yarn run typeorm-ts migration:generate -n ",
1414
"db:entity:new": "yarn run typeorm-ts entity:create -n ",
1515
"db:subscriber:new": "yarn run typeorm-ts subscriber:create -n ",
1616
"db:migrate": "npx task npm typeorm-ts migration:run",

src/services/db/index.ts

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,22 @@
1-
import {Connection, createConnection, getConnectionOptions} from "typeorm";
1+
import {Connection, createConnection, getConnectionOptions, ObjectType, getConnection} from "typeorm";
22
import {sleep} from "../utils";
33
import {logger} from "../logger";
44
import {PostgresConnectionCredentialsOptions} from "typeorm/driver/postgres/PostgresConnectionCredentialsOptions";
55
import {TypeOrmLogger} from "../logger/typeorm";
66

77
export async function getDatabaseConnection(): Promise<Connection> {
88
const opts = await getConnectionOptions();
9-
let conn = await createConnection({
10-
...opts,
11-
logger: new TypeOrmLogger()
12-
});
13-
conn = await openConnection(conn);
14-
await conn.runMigrations({transaction: "all"});
9+
let conn: Connection;
10+
try {
11+
conn = getConnection();
12+
} catch{
13+
conn = await createConnection({
14+
...opts,
15+
logger: new TypeOrmLogger()
16+
});
17+
conn = await openConnection(conn);
18+
await conn.runMigrations({transaction: "all"});
19+
}
1520
return conn;
1621
}
1722

@@ -28,4 +33,9 @@ async function openConnection(conn: Connection): Promise<Connection> {
2833
await sleep(3000);
2934
return openConnection(conn);
3035
}
31-
}
36+
}
37+
38+
export async function getRepository<T>(customRepository: ObjectType<T>): Promise<T> {
39+
const connection = await getDatabaseConnection();
40+
return connection.getCustomRepository<T>(customRepository);
41+
}

0 commit comments

Comments
 (0)