forked from grrr-amsterdam/mysql-ssh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql.js
78 lines (66 loc) · 2.13 KB
/
mysql.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
#!/usr/bin/env node
/**
* @author David Spreekmeester <[email protected]>
*/
const mysql = require('mysql2')
const Client = require('ssh2').Client;
var tunnel = module.exports = {
/**
* @var ssh2.Connection _conn The SSH connection
*/
_conn: null,
/**
* @var mysql2.Connection _conn The MySQL connection
*/
_sql: 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 connection>
*/
connect: function(sshConfig, dbConfig) {
dbConfig = tunnel._addDefaults(dbConfig)
return new Promise(function(resolve, reject) {
tunnel._conn = new Client();
tunnel._conn.on('ready', function() {
tunnel._conn.forwardOut(
'127.0.0.1',
12345,
dbConfig.host,
dbConfig.port,
function (err, stream) {
if (err) {
tunnel.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 = stream
tunnel._sql = mysql.createConnection(dbConfig)
resolve(tunnel._sql)
}
)
}).connect(sshConfig)
})
},
close: function() {
if ('end' in tunnel._sql) {
tunnel._sql.end(function(err) {})
}
if ('end' in tunnel._conn) {
tunnel._conn.end()
}
},
_addDefaults(dbConfig) {
if (!('port' in dbConfig)) {
dbConfig.port = 3306
}
if (!('host' in dbConfig)) {
dbConfig.host = 'localhost'
}
return dbConfig
}
}