Skip to content

Commit 849d844

Browse files
author
Peter Svetlichny
committed
refactor(postgres): use pg.Pool to manage connections
1 parent 8fa894e commit 849d844

File tree

1 file changed

+16
-15
lines changed

1 file changed

+16
-15
lines changed

src/index.js

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const pg = require('pg')
1+
const { Pool } = require('pg')
22

33
/**
44
* @class postgres
@@ -13,7 +13,7 @@ module.exports = class {
1313
* @param {String} config.database The connection database
1414
*/
1515
constructor (config) {
16-
this.pg = new pg.Client(config)
16+
this.pg = new Pool(config)
1717
}
1818

1919
/**
@@ -22,18 +22,19 @@ module.exports = class {
2222
* @returns {Object} promise
2323
*/
2424
query (query) {
25-
let res
26-
// TODO: overlapping connections
25+
let client
2726
return this.pg.connect()
28-
.then(() => this.pg.query(query))
29-
.then(data => {
30-
res = data
31-
return this.pg.end()
27+
.then((cli) => {
28+
client = cli
29+
return client.query(query)
30+
})
31+
.then(res => {
32+
client.release()
33+
return res
3234
})
33-
.then(() => res)
3435
.catch((err) => {
35-
return this.pg.end()
36-
.then(() => { throw err })
36+
client.release()
37+
throw err
3738
})
3839
}
3940

@@ -105,11 +106,11 @@ module.exports = class {
105106
.then(data => {
106107
let i = 1
107108
let changes = ''
108-
let len = Object.keys(body).length
109-
for (let prop in body) {
110-
if ({}.hasOwnProperty.call(body, prop)) {
109+
let len = Object.keys(data).length
110+
for (let prop in data) {
111+
if ({}.hasOwnProperty.call(data, prop)) {
111112
let comma = (i !== len) ? ', ' : ''
112-
changes += `${prop}='${body[prop]}'${comma}`
113+
changes += `${prop}='${data[prop]}'${comma}`
113114
i++
114115
}
115116
}

0 commit comments

Comments
 (0)