/
parse-connection.js
87 lines (80 loc) · 1.94 KB
/
parse-connection.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
79
80
81
82
83
84
85
86
87
const { parse } = require('pg-connection-string');
const parsePG = parse;
const isWindows = process && process.platform && process.platform === 'win32';
/**
* @param str
* @returns {URL}
*/
function tryParse(str) {
try {
return new URL(str);
} catch (e) {
return null;
}
}
module.exports = function parseConnectionString(str) {
const parsed = tryParse(str);
const isDriveLetter = isWindows && parsed && parsed.protocol.length === 2;
if (!parsed || isDriveLetter) {
return {
client: 'sqlite3',
connection: {
filename: str,
},
};
}
let { protocol } = parsed;
if (protocol.slice(-1) === ':') {
protocol = protocol.slice(0, -1);
}
const isPG = ['postgresql', 'postgres'].includes(protocol);
return {
client: protocol,
connection: isPG ? parsePG(str) : connectionObject(parsed),
};
};
/**
* @param {URL} parsed
* @returns {{}}
*/
function connectionObject(parsed) {
const connection = {};
let db = parsed.pathname;
if (db[0] === '/') {
db = db.slice(1);
}
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.username || parsed.password) {
connection.user = decodeURIComponent(parsed.username);
}
if (parsed.password) {
connection.password = decodeURIComponent(parsed.password);
}
if (parsed.searchParams) {
for (const [key, value] of parsed.searchParams.entries()) {
const isNestedConfigSupported = ['mysql:', 'mariadb:', 'mssql:'].includes(
parsed.protocol
);
if (isNestedConfigSupported) {
try {
connection[key] = JSON.parse(value);
} catch (err) {
connection[key] = value;
}
} else {
connection[key] = value;
}
}
}
return connection;
}