@@ -17,42 +17,26 @@ function connectDb(connectionString, caCert) {
1717 } ;
1818
1919 // set up a new client using our config details
20- let client = new Pool ( postgreConfig ) ;
20+ let pool = new Pool ( { ... postgreConfig , max : 20 , idleTimeoutMillis : 5000 , connectionTimeoutMillis : 2000 } ) ;
2121
22- client . connect ( ( err ) => {
23- if ( err ) {
24- console . error ( `Failed to connect to postgreSQL host '${ postgreConfig . host } '` , err ) ;
25- return reject ( err ) ;
26- }
27-
28- client . query (
29- "CREATE TABLE IF NOT EXISTS users (firstname varchar(256) NOT NULL, lastname varchar(256) NOT NULL)" ,
30- ( err , result ) => {
31- if ( err ) {
32- console . log ( `Failed to create PostgreSQL table 'users'` , err ) ;
33- return reject ( err ) ;
34- }
35- console . log (
36- `Established PostgreSQL client connection to '${ postgreConfig . host } ' - user table init: ${ JSON . stringify (
37- result
38- ) } `
39- ) ;
40- return resolve ( client ) ;
22+ pool . query (
23+ "CREATE TABLE IF NOT EXISTS users (firstname varchar(256) NOT NULL, lastname varchar(256) NOT NULL)" ,
24+ ( err , result ) => {
25+ if ( err ) {
26+ console . log ( `Failed to create PostgreSQL table 'users'` , err ) ;
27+ return reject ( err ) ;
4128 }
42- ) ;
43- } ) ;
29+ console . log (
30+ `Established PostgreSQL client connection to '${ postgreConfig . host } ' - user table init: ${ JSON . stringify (
31+ result
32+ ) } `
33+ ) ;
34+ return resolve ( pool ) ;
35+ }
36+ ) ;
4437 } ) ;
4538}
4639
47- export async function closeDBConnection ( ) {
48- if ( _pgPool ) {
49- console . log ( "Draining PG pool." ) ;
50- await _pgPool . end ( ) ;
51- console . log ( "PG pool has drained." ) ;
52- }
53- Promise . resolve ( ) ;
54- }
55-
5640export async function getPgClient ( secretsManager , secretId ) {
5741 const fn = "getPgClient " ;
5842 const startTime = Date . now ( ) ;
@@ -81,6 +65,10 @@ export async function getPgClient(secretsManager, secretId) {
8165 const pgConnectionString = res . result . credentials . connection . postgres . composed [ 0 ] ;
8266 _pgPool = await connectDb ( pgConnectionString , pgCaCert ) ;
8367
68+ _pgPool . on ( "error" , ( err ) => {
69+ console . log ( "Pool received an error event" , err ) ;
70+ } ) ;
71+
8472 console . log ( `${ fn } < done - duration ${ Date . now ( ) - startTime } ms` ) ;
8573 return _pgPool ;
8674}
@@ -134,3 +122,11 @@ export function deleteUsers(client) {
134122 } ) ;
135123 } ) ;
136124}
125+
126+ export async function closeDBConnection ( ) {
127+ if ( _pgPool ) {
128+ console . log ( "Draining PG pool..." ) ;
129+ await _pgPool . end ( ) ;
130+ console . log ( "PG pool has drained." ) ;
131+ }
132+ }
0 commit comments