index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. var mysql = require('mysql2');
  2. function wrap (fn, ctx) {
  3. return function () {
  4. var args = [].slice.call(arguments);
  5. return function (done) {
  6. args.push(done);
  7. fn.apply(ctx, args);
  8. };
  9. };
  10. }
  11. var methods = [
  12. 'query',
  13. 'execute'
  14. ];
  15. function wrapConnection(conn) {
  16. if (conn._coWrapped)
  17. return conn;
  18. conn._coWrapped = true;
  19. methods.forEach(function (name) {
  20. conn[name] = wrap(conn[name], conn);
  21. });
  22. return conn;
  23. }
  24. module.exports = {
  25. createConnection: function(opts) {
  26. return wrapConnection(mysql.createConnection(opts));
  27. },
  28. simplePool: function(opts) {
  29. var pool = mysql.createPool(opts);
  30. function wrapPooledFunc(func, sql, params) {
  31. return function(done) {
  32. pool.getConnection(function(err, connection) {
  33. if (err)
  34. return done(err);
  35. connection[func](sql, params, function(err, rows, fields, numStatements) {
  36. if (err)
  37. return done(err);
  38. connection.end();
  39. return done(null, rows, fields, numStatements);
  40. });
  41. });
  42. };
  43. }
  44. return {
  45. query: function(sql, params) {
  46. return wrapPooledFunc('query', sql, params);
  47. },
  48. execute: function(sql, params) {
  49. return wrapPooledFunc('execute', sql, params);
  50. },
  51. end: function() {
  52. pool.end();
  53. }
  54. };
  55. },
  56. createPool: function(opts) {
  57. var pool = mysql.createPool(opts);
  58. var getConn = pool.getConnection;
  59. var wrappedGetConnection = function() {
  60. return function(done) {
  61. getConn.call(pool, function(err, conn) {
  62. if (err) return done(err);
  63. return done(null, wrapConnection(conn));
  64. });
  65. };
  66. };
  67. pool.getConnection = wrappedGetConnection;
  68. return pool;
  69. }
  70. };