Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. const mysql = require('mysql2')
  2. const tunnel = require('tunnel-ssh')
  3.  
  4. const ssh2mysql = {
  5. _conn: null,
  6.  
  7. _mysql_pool: null,
  8.  
  9. /**
  10. * @param obj sshConfig SSH Configuration as defined by ssh2 package
  11. * @param obj dbConfig MySQL Configuration as defined by mysql(2) package
  12. * @return Promise
  13. */
  14. connect: function(sshConfig, dbConfig) {
  15. dbConfig = ssh2mysql._addDefaultsDBConfig(dbConfig)
  16. sshConfig = ssh2mysql._addDefaultsSSHConfig(sshConfig)
  17. return new Promise(function(resolve, reject) {
  18. ssh2mysql._conn = new tunnel(sshConfig, (error, tnl) => {
  19. if (error) {
  20. ssh2mysql.close()
  21. var msg =
  22. error.reason == 'CONNECT_FAILED' ? 'Connection failed.' : error
  23. return reject(msg)
  24. }
  25.  
  26. ssh2mysql._mysql_pool = mysql.createPool(dbConfig)
  27.  
  28. const execSql = sql => {
  29. return new Promise((resolve, reject) => {
  30. ssh2mysql._mysql_pool.getConnection(function(err, conn) {
  31. if (err) {
  32. reject(err)
  33. ssh2mysql._mysql_pool.releaseConnection(conn)
  34. }
  35. conn.query(sql, (error, results) => {
  36. if (error) {
  37. reject(error)
  38. } else {
  39. resolve(results)
  40. }
  41. ssh2mysql._mysql_pool.releaseConnection(conn)
  42. })
  43. })
  44. })
  45. }
  46. resolve({ execSql })
  47. })
  48. })
  49. },
  50.  
  51. close: function() {
  52. if ('end' in ssh2mysql._mysql_pool) {
  53. ssh2mysql._mysql_pool.end(() => {})
  54. }
  55. if ('end' in ssh2mysql._conn) {
  56. ssh2mysql._conn.end()
  57. }
  58. },
  59.  
  60. _addDefaultsSSHConfig(sshConfig) {
  61. return Object.assign(
  62. { keepAlive: true, localHost: '127.0.0.1', localPort: 12345, port: 22 },
  63. sshConfig,
  64. )
  65. },
  66.  
  67. _addDefaultsDBConfig(dbConfig) {
  68. return Object.assign({ host: 'localhost', port: 3306 }, dbConfig)
  69. },
  70. }
  71.  
  72. export default ssh2mysql
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement