-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.js
42 lines (39 loc) · 1.8 KB
/
db.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
const pg = require('pg');
pg.defaults.ssl = process.env.DATABASE_URL ? process.env.DATABASE_UR: true;
// create a config to configure both pooling behavior
// and client options
// note: all config is optional and the environment variables
// will be read if the config is not present
var urlMatch = /postgres:\/\/(\w+):(\w+)@(.+):(.+)\/(.+)/;
var match = urlMatch.exec(process.env.DATABASE_URL);
var config = {
user: match[1], //env var: PGUSER
database: match[5], //env var: PGDATABASE
password: match[2], //env var: PGPASSWORD
host: match[3], // Server hosting the postgres database
port: match[4], //env var: PGPORT
max: 10, // max number of clients in the pool
//idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed
};
//this initializes a connection pool
//it will keep idle connections open for 30 seconds
//and set a limit of maximum 10 idle clients
const pool = new pg.Pool(config);
pool.on('error', function (err, client) {
// if an error is encountered by a client while it sits idle in the pool
// the pool itself will emit an error event with both the error and
// the client which emitted the original error
// this is a rare occurrence but can happen if there is a network partition
// between your application and the database, the database restarts, etc.
// and so you might want to handle it and at least log it out
console.error('idle client error', err.message, err.stack);
});
//export the query method for passing queries to the pool
module.exports.query = function (text, values, callback) {
return pool.query(text, values, callback);
};
// the pool also supports checking out a client for
// multiple operations, such as a transaction
module.exports.connect = function (callback) {
return pool.connect(callback);
};