index.js
1.65 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
62
'use strict';
var url = require('url');
//Parse method copied from https://github.com/brianc/node-postgres
//Copyright (c) 2010-2014 Brian Carlson (brian.m.carlson@gmail.com)
//MIT License
//parses a connection string
function parse(str) {
var config;
//unix socket
if(str.charAt(0) === '/') {
config = str.split(' ');
return { host: config[0], database: config[1] };
}
// url parse expects spaces encoded as %20
if(/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str)) {
str = encodeURI(str).replace(/\%25(\d\d)/g, "%$1");
}
var result = url.parse(str, true);
config = {};
if (result.query.application_name) {
config.application_name = result.query.application_name;
}
if (result.query.fallback_application_name) {
config.fallback_application_name = result.query.fallback_application_name;
}
config.port = result.port;
if(result.protocol == 'socket:') {
config.host = decodeURI(result.pathname);
config.database = result.query.db;
config.client_encoding = result.query.encoding;
return config;
}
config.host = result.hostname;
// result.pathname is not always guaranteed to have a '/' prefix (e.g. relative urls)
// only strip the slash if it is present.
var pathname = result.pathname;
if (pathname && pathname.charAt(0) === '/') {
pathname = result.pathname.slice(1) || null;
}
config.database = pathname && decodeURI(pathname);
var auth = (result.auth || ':').split(':');
config.user = auth[0];
config.password = auth.splice(1).join(':');
var ssl = result.query.ssl;
if (ssl === 'true' || ssl === '1') {
config.ssl = true;
}
return config;
}
module.exports = {
parse: parse
};