Skip to content

Commit 41872c7

Browse files
authored
Merge pull request #52 from daeisbae/48-change-db-pool-implementation
Change it to singleton based pool db (#48)
2 parents 06264d9 + 1d9e38b commit 41872c7

File tree

1 file changed

+40
-7
lines changed

1 file changed

+40
-7
lines changed

src/db/utils/connector.ts

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,44 @@
1-
import { Pool, QueryResult } from 'pg'
1+
import pg, { QueryResult } from 'pg'
2+
// import { promises as fs } from 'fs'
3+
import {readFileSync} from 'fs'
24
import { DBConfig } from '@/db/config/config'
5+
import { promises as fs } from 'fs'
36

47
/**
58
* Database connection handler (Instance pattern - Although not recommended due to thread issue, this is currently the best solution)
69
* @class DatabaseConnector
710
*/
811
class DBConnector {
9-
private pool: Pool
12+
private pool: pg.Pool
13+
private conn: boolean
14+
private static instance: DBConnector
1015

1116
/**
1217
* Creates a new database connection pool
1318
* @constructor
1419
*/
15-
constructor() {
16-
this.pool = new Pool(DBConfig)
20+
private constructor() {
21+
const { Pool } = pg
22+
this.conn = false
23+
this.pool = new Pool({...DBConfig, ...{
24+
ssl: {
25+
rejectUnauthorized: false,
26+
ca: fs.readFile(process.cwd() + '/src/assets/ca-certificate.crt')
27+
.toString(),
28+
sslmode: 'require',
29+
},
30+
}})
31+
}
32+
33+
/**
34+
* Get the instance of the database connector
35+
* @returns The database connector instance
36+
*/
37+
static getInstance(): DBConnector {
38+
if (!DBConnector.instance) {
39+
DBConnector.instance = new DBConnector()
40+
}
41+
return DBConnector.instance
1742
}
1843

1944
/**
@@ -27,10 +52,17 @@ class DBConnector {
2752
text: string,
2853
params?: any[]
2954
): Promise<QueryResult<T>> {
55+
let client: pg.PoolClient | undefined = undefined
3056
try {
31-
return await this.pool.query(text, params)
57+
client = await this.pool.connect()
58+
this.conn = true
59+
const result = await this.pool.query(text, params)
60+
await client.release()
61+
this.conn = false
62+
return result
3263
} catch (error) {
33-
throw new Error(
64+
this.conn && client.release()
65+
console.log(
3466
`Database query failed: ${
3567
error instanceof Error ? error.message : 'Unknown error'
3668
}`
@@ -39,4 +71,5 @@ class DBConnector {
3971
}
4072
}
4173

42-
export default new DBConnector()
74+
// eslint-disable-next-line import/no-anonymous-default-export
75+
export default DBConnector.getInstance()

0 commit comments

Comments
 (0)