-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
78 lines (70 loc) · 1.78 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
var mysql = require('mysql2');
function wrap (fn, ctx) {
return function () {
var args = [].slice.call(arguments);
return function (done) {
args.push(done);
fn.apply(ctx, args);
};
};
}
var methods = [
'query',
'execute'
];
function wrapConnection(conn) {
if (conn._coWrapped)
return conn;
conn._coWrapped = true;
methods.forEach(function (name) {
conn[name] = wrap(conn[name], conn);
});
return conn;
}
module.exports = {
createConnection: function(opts) {
return wrapConnection(mysql.createConnection(opts));
},
simplePool: function(opts) {
var pool = mysql.createPool(opts);
function wrapPooledFunc(func, sql, params) {
return function(done) {
pool.getConnection(function(err, connection) {
if (err)
return done(err);
connection[func](sql, params, function(err, rows, fields, numStatements) {
if (err)
return done(err);
connection.release();
return done(null, rows, fields, numStatements);
});
});
};
}
return {
query: function(sql, params) {
return wrapPooledFunc('query', sql, params);
},
execute: function(sql, params) {
return wrapPooledFunc('execute', sql, params);
},
end: function() {
pool.end();
}
};
},
createPool: function(opts) {
var pool = mysql.createPool(opts);
var getConn = pool.getConnection;
var wrappedGetConnection = function() {
return function(done) {
getConn.call(pool, function(err, conn) {
if (err) return done(err);
return done(null, wrapConnection(conn));
});
};
};
pool.getConnection = wrappedGetConnection;
return pool;
}
};