-
Notifications
You must be signed in to change notification settings - Fork 0
/
db-middleware.js
108 lines (79 loc) · 2.14 KB
/
db-middleware.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
var mysql = require('mysql'),
Promise = require('bluebird');
function getMysqlConnection(key, pool) {
return pool.getConnectionAsync()
.then(function(connection) {
//TODO store the connections by key
//TODO what to do if connection aborded ??? we need to release some how ???
//TODO This should be probably done at the appending to the request
if (!connection) {
throw new Error("no connection received");
}
//TODO this should not happen we need to test this at the assigning
// and release if connection is closed (request is finished)
return {
key: key,
connection: connection
};
});
}
function setup(options) {
var pools = [];
require('mysql-additions').enable({
experimental: true,
legacyPromise: options.legacyPromise || false
});
for (var key in options.dbs) {
if (options.dbs.hasOwnProperty(key)) {
//TODO check the engine !!!!!
pools.push({
key: key,
pool: mysql.createPool(options.dbs[key]),
cb: getMysqlConnection
});
}
}
function getConnections() {
var connections = [];
pools.forEach(function(pool) {
connections.push(pool.cb(pool.key, pool.pool));
});
return Promise.all(connections);
}
function releaseDbs() {
if (this._dbs) {
for (var key in this._dbs) {
if (this._dbs.hasOwnProperty(key)) {
this._dbs[key].release();
}
}
this._dbs = undefined;
}
}
function db(key) {
return this._dbs[key];
}
return function(req, res, next) {
var end = res.end;
getConnections()
.then(function(dbs) {
req._dbs = {};
//TODO check if request is alive and response was not send !!!!
dbs.forEach(function(value) {
req._dbs[value.key] = value.connection;
});
next();
}, function(e) {
next(new Error("connections could not be opened"));
});
req.db = db;
res.on("close", function() {
releaseDbs.call(req);
});
res.end = function(chunk, encoding) {
releaseDbs.call(req);
end.apply(res, arguments);
};
};
}
exports.setup = setup;