1
- import { Pool } from 'pg' ;
1
+ import { Pool , Client } from 'pg' ;
2
+ import retry from 'async-retry' ;
2
3
import { ServiceError } from 'errors/index.js' ;
3
4
4
- const poolConfiguration = {
5
+ const configurations = {
5
6
user : process . env . POSTGRES_USER ,
6
7
host : process . env . POSTGRES_HOST ,
7
8
database : process . env . POSTGRES_DB ,
@@ -15,14 +16,17 @@ const poolConfiguration = {
15
16
16
17
// https://github.com/filipedeschamps/tabnews.com.br/issues/84
17
18
if ( [ 'test' , 'development' ] . includes ( process . env . NODE_ENV ) || process . env . CI ) {
18
- delete poolConfiguration . ssl ;
19
+ delete configurations . ssl ;
19
20
}
20
21
21
- const pool = new Pool ( poolConfiguration ) ;
22
+ const pool = new Pool ( configurations ) ;
22
23
23
24
async function query ( query , params ) {
25
+ let clientFromPool ;
26
+
24
27
try {
25
- return await pool . query ( query , params ) ;
28
+ clientFromPool = await tryToGetNewClientFromPool ( ) ;
29
+ return await clientFromPool . query ( query , params ) ;
26
30
} catch ( error ) {
27
31
const errorObject = new ServiceError ( {
28
32
message : error . message ,
@@ -34,15 +38,31 @@ async function query(query, params) {
34
38
} ) ;
35
39
console . error ( errorObject ) ;
36
40
throw errorObject ;
41
+ } finally {
42
+ if ( clientFromPool ) {
43
+ clientFromPool . release ( ) ;
44
+ }
37
45
}
38
46
}
39
47
40
- async function getNewConnectedClient ( ) {
41
- // When manually creating a new connection like this,
42
- // you need to make sure to close it afterward
43
- // with the .end() method.
44
- try {
48
+ async function tryToGetNewClientFromPool ( ) {
49
+ const clientFromPool = await retry ( newClientFromPool , {
50
+ retries : 50 ,
51
+ minTimeout : 0 ,
52
+ factor : 1.3 ,
53
+ } ) ;
54
+
55
+ return clientFromPool ;
56
+
57
+ async function newClientFromPool ( ) {
45
58
return await pool . connect ( ) ;
59
+ }
60
+ }
61
+
62
+ async function getNewClient ( ) {
63
+ try {
64
+ const client = await tryToGetNewClient ( ) ;
65
+ return client ;
46
66
} catch ( error ) {
47
67
const errorObject = new ServiceError ( {
48
68
message : error . message ,
@@ -52,9 +72,25 @@ async function getNewConnectedClient() {
52
72
console . error ( errorObject ) ;
53
73
throw errorObject ;
54
74
}
75
+
76
+ async function tryToGetNewClient ( ) {
77
+ const client = await retry ( newClient , {
78
+ retries : 50 ,
79
+ minTimeout : 0 ,
80
+ factor : 1.3 ,
81
+ } ) ;
82
+
83
+ return client ;
84
+
85
+ async function newClient ( ) {
86
+ const client = new Client ( configurations ) ;
87
+ await client . connect ( ) ;
88
+ return client ;
89
+ }
90
+ }
55
91
}
56
92
57
93
export default Object . freeze ( {
58
94
query,
59
- getNewConnectedClient ,
95
+ getNewClient ,
60
96
} ) ;
0 commit comments