Created
September 7, 2019 05:19
-
-
Save hjzheng/6ab3df05018a8f57dc2fc43b36d29976 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as mysql from 'mysql2' | |
const Client = require('ssh2').Client | |
const ssh2mysql = { | |
_conn: null, | |
_mysql_conn: null, | |
/** | |
* @param obj sshConfig SSH Configuration as defined by ssh2 package | |
* @param obj dbConfig MySQL Configuration as defined by mysql(2) package | |
* @return Promise <mysql2 conn> | |
*/ | |
connect: function(sshConfig, dbConfig) { | |
dbConfig = ssh2mysql._addDefaults(dbConfig) | |
return new Promise(function(resolve, reject) { | |
ssh2mysql._conn = new Client() | |
ssh2mysql._conn | |
.on('ready', function() { | |
ssh2mysql._conn.forwardOut( | |
'127.0.0.1', | |
12345, | |
dbConfig.host, | |
dbConfig.port, | |
function(err, stream) { | |
if (err) { | |
ssh2mysql.close() | |
var msg = | |
err.reason == 'CONNECT_FAILED' ? 'Connection failed.' : err | |
return reject(msg) | |
} | |
// override db host, since we're operating from within the SSH tunnel | |
dbConfig.host = 'localhost' | |
dbConfig.stream = function() { | |
return stream | |
} | |
// 这种方式不支持数据库连接池 | |
// https://github.com/sidorares/node-mysql2/issues/653 | |
ssh2mysql._mysql_conn = mysql.createConnection(dbConfig) | |
const execSql = sql => { | |
return new Promise((resolve, reject) => { | |
ssh2mysql._mysql_conn.query(sql, (error, results) => { | |
if (error) { | |
reject(error) | |
} else { | |
resolve(results) | |
} | |
}) | |
}) | |
} | |
resolve({ execSql }) | |
}, | |
) | |
}) | |
.connect(sshConfig) | |
}) | |
}, | |
close: function() { | |
if ('end' in ssh2mysql._mysql_conn) { | |
ssh2mysql._mysql_conn.end() | |
} | |
if ('end' in ssh2mysql._conn) { | |
ssh2mysql._conn.end() | |
} | |
}, | |
_addDefaults(dbConfig) { | |
if (!('port' in dbConfig)) { | |
dbConfig.port = 3306 | |
} | |
if (!('host' in dbConfig)) { | |
dbConfig.host = 'localhost' | |
} | |
return dbConfig | |
}, | |
} | |
export default ssh2mysql |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment