forked from samson-teals/url-shorten
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpgdb.js
61 lines (49 loc) · 1.24 KB
/
pgdb.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const { Client, Pool } = require('pg')
class pgdb {
constructor(config = {}) {
// heroku support
if (!config.connectionString && process.env.DATABASE_URL) {
config.connectionString = process.env.DATABASE_URL;
config.ssl = true;
}
this._clientConfig = config;
this._poolConfig = config;
}
pool() {
if (!this._pool) {
this._pool = new Pool(this._poolConfig);
}
return this._pool;
}
// remember to client.release() when done
async client() {
return this.pool().connect();
}
async end() {
if (this._pool) {
await this._pool.end();
this._pool = null;
}
}
// use pool.query - no need to release, but not transaction safe
async query(str, args = []) {
return this.pool().query(str, args);
}
/////////////////////////////////////////////////////////
// Direct connection if required
/////////////////////////////////////////////////////////
async direct_client() {
if (!this._client) {
this._client = new Client(this._clientConfig);
await this._client.connect();
}
return this._client;
}
async direct_end() {
if (this._client) {
await this._client.end();
this._client = null;
}
}
}
module.exports = pgdb;