parse-connection.js
1.38 KB
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
import url from 'url'
import { parse as parsePG } from 'pg-connection-string'
export default function parseConnectionString(str) {
const parsed = url.parse(str)
let { protocol } = parsed
if (protocol && protocol.indexOf('maria') === 0) {
protocol = 'maria'
}
if (protocol === null) {
return {
client: 'sqlite3',
connection: {
filename: str
}
}
}
if (protocol.slice(-1) === ':') {
protocol = protocol.slice(0, -1);
}
return {
client: protocol,
connection: protocol === 'postgres' ? parsePG(str) : connectionObject(parsed)
}
}
function connectionObject(parsed) {
const connection = {};
let db = parsed.pathname;
if (db[0] === '/') {
db = db.slice(1)
}
if (parsed.protocol.indexOf('maria') === 0) {
connection.db = db
} else {
connection.database = db
}
if (parsed.hostname) {
if (parsed.protocol.indexOf('mssql') === 0) {
connection.server = parsed.hostname;
} else {
connection.host = parsed.hostname;
}
}
if (parsed.port) {
connection.port = parsed.port;
}
if (parsed.auth) {
const idx = parsed.auth.indexOf(':');
if (idx !== -1) {
connection.user = parsed.auth.slice(0, idx);
if (idx < parsed.auth.length - 1) {
connection.password = parsed.auth.slice(idx + 1);
}
} else {
connection.user = parsed.auth;
}
}
return connection
}