-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
120 lines (99 loc) · 2.36 KB
/
index.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
'use strict';
var DSNParser = function (dsn) {
this.dsn = dsn || '';
this.parts = {
'driver': null,
'user': null,
'password': null,
'host': null,
'port': null,
'database': null,
'params': {}
};
if (this.dsn) {
this.parse();
}
};
DSNParser.prototype.parse = function () {
var regexp = new RegExp(
'^' +
'(?:' +
'([^:\/?#.]+)' + // driver
':)?' +
'(?:\/\/' +
'(?:([^\/?#]*)@)?' + // auth
'([\\w\\d\\-\\u0100-\\uffff.%]*)' + // host
'(?::([0-9]+))?' + // port
')?' +
'([^?#]+)?' + // database
'(?:\\?([^#]*))?' + // params
'$'
);
var split = this.dsn.match(regexp);
var auth = split[2]?split[2].split(':'):[];
this.parts = {
'driver': split[1],
'user': auth[0] || null,
'password': auth[1] || null,
'host': split[3],
'port': split[4] ? parseInt(split[4], 10) : null,
'database': stripLeadingSlash(split[5]),
'params': fromQueryParams(split[6])
};
return this;
};
DSNParser.prototype.get = function (prop, def) {
if (typeof(this.parts[prop]) !== 'undefined') {
if (this.parts[prop] === null) {
return def;
} else {
return this.parts[prop];
}
} else
if (typeof(def) !== 'undefined') {
return def;
}
return null;
};
DSNParser.prototype.set = function (prop, value) {
this.parts[prop] = value;
return this;
};
DSNParser.prototype.getDSN = function () {
var dsn = (this.parts.driver || '') + ':https://'
+ (this.parts.user ? (
(this.parts.user || '')
+ (this.parts.password ? ':' + this.parts.password : '') + '@')
: '')
+ (this.parts.host || '')
+ (this.parts.port ? ':' + this.parts.port : '') + '/'
+ (this.parts.database || '');
if (this.parts.params && Object.keys(this.parts.params).length > 0) {
dsn += '?' + toQueryParams(this.parts.params);
}
return dsn;
};
DSNParser.prototype.getParts = function () {
return this.parts;
};
function fromQueryParams (params) {
if (!params) {
return {};
}
return JSON.parse('{"' + decodeURI(params).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}');
}
function toQueryParams (obj) {
var str = [];
for (var p in obj) {
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
}
return str.join('&');
}
function stripLeadingSlash (str) {
str = str || '';
if (str.substr(0, 1) === '/') {
return str.substr(1, str.length);
}
return str;
}
module.exports = DSNParser;