-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
84 lines (73 loc) · 1.94 KB
/
index.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
var pg = require('pg'),
util = require('util'),
once = require('once'),
apiErrors = require('api-errors'),
logger = require('logtastic');
var pgc = module.exports = function(options) {
options = options || {};
pgc.ssl = options.ssl || false;
if (options.url) {
pgc.connectionString = options.url;
}
else
{ pgc.user = options.user || process.env.POSTGRES_USER;
pgc.password = options.password || process.env.POSTGRES_PASSWORD;
pgc.host = options.host || process.env.POSTGRES_HOST;
pgc.db = options.db || process.env.POSTGRES_DB;
pgc.connectionString = util.format('postgres://%s:%s@%s/%s', pgc.user, pgc.password, pgc.host, pgc.db);
}
return pgc;
};
// Get a connection, log err on failure
pgc.connect = function(done) {
if (pgc.ssl) {
pg.defaults.ssl = true;
}
pg.connect(pgc.connectionString, function(err, client, release) {
if (err) {
logger.error(err, {
connString: pgc.connectionString
});
return done(err);
}
done(null, client, release);
});
};
// A middleware generator with options
pgc.middleware = function(options) {
options = options || {};
return function(req, res, next) {
pgc.connect(function(err, conn, release) {
if (err) {
// The error is logged inside db
return apiErrors.e500(res, {
message: 'Error connecting to database',
code: 'db-conn-error',
});
}
// Only call release once
release = once(release);
// Start timeout if one was set
var _to;
if (options.releaseIn) {
_to = setTimeout(function() {
logger.warning('DB connection released after timeout');
req.db = null;
release();
}, options.releaseIn);
}
// Release on close
if (options.releaseOnClose !== false) {
res.on('finish', function() {
logger.debug('Releasing db connection on finish');
clearTimeout(_to);
req.db = null;
release();
});
}
// Add connection to request object
req[options.key || 'db'] = conn;
next();
});
};
};