UNPKG

1.45 kBJavaScriptView Raw
1const url = require('url');
2const { parse } = require('pg-connection-string');
3const parsePG = parse;
4
5module.exports = function parseConnectionString(str) {
6 const parsed = url.parse(str, true);
7 let { protocol } = parsed;
8 if (protocol === null) {
9 return {
10 client: 'sqlite3',
11 connection: {
12 filename: str,
13 },
14 };
15 }
16 if (protocol.slice(-1) === ':') {
17 protocol = protocol.slice(0, -1);
18 }
19
20 const isPG = ['postgresql', 'postgres'].includes(protocol);
21
22 return {
23 client: protocol,
24 connection: isPG ? parsePG(str) : connectionObject(parsed),
25 };
26};
27
28function connectionObject(parsed) {
29 const connection = {};
30 let db = parsed.pathname;
31 if (db[0] === '/') {
32 db = db.slice(1);
33 }
34
35 connection.database = db;
36
37 if (parsed.hostname) {
38 if (parsed.protocol.indexOf('mssql') === 0) {
39 connection.server = parsed.hostname;
40 } else {
41 connection.host = parsed.hostname;
42 }
43 }
44 if (parsed.port) {
45 connection.port = parsed.port;
46 }
47 if (parsed.auth) {
48 const idx = parsed.auth.indexOf(':');
49 if (idx !== -1) {
50 connection.user = parsed.auth.slice(0, idx);
51 if (idx < parsed.auth.length - 1) {
52 connection.password = parsed.auth.slice(idx + 1);
53 }
54 } else {
55 connection.user = parsed.auth;
56 }
57 }
58 if (parsed.query) {
59 for (const key in parsed.query) {
60 connection[key] = parsed.query[key];
61 }
62 }
63 return connection;
64}