-
-
Notifications
You must be signed in to change notification settings - Fork 144
/
db.js
59 lines (47 loc) · 1.4 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const EventEmitter = require('events');
const pg = require('pg');
const Promise = require('bluebird');
const url = require('url');
class Db extends EventEmitter {
constructor(config){
super();
this.config = config;
let poolConfig = (config.connectionString)
? parseConnectionString(config.connectionString)
: config;
this.pool = new pg.Pool({
user: poolConfig.user,
password: poolConfig.password,
host: poolConfig.host,
port: poolConfig.port,
database: poolConfig.database,
application_name: poolConfig.application_name || 'pgboss',
max: poolConfig.poolSize,
ssl: !!poolConfig.ssl,
Promise
});
this.pool.on('error', error => this.emit('error', error));
function parseConnectionString(connectionString){
const parseQuerystring = true;
const params = url.parse(connectionString, parseQuerystring);
const auth = params.auth.split(':');
return {
user: auth[0],
password: auth[1],
host: params.hostname,
port: params.port,
database: params.pathname.split('/')[1],
ssl: !!params.query.ssl
};
}
}
close(){
return !this.pool.ending ? this.pool.end() : Promise.resolve(true);
}
executeSql(text, values) {
if(values && !Array.isArray(values))
values = [values];
return this.pool.query(text, values);
}
}
module.exports = Db;