Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use WHATWG URL parsing, if available, instead of url.parse #2564

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 26 additions & 3 deletions lib/ConnectionConfig.js
Expand Up @@ -177,21 +177,34 @@ ConnectionConfig.parseFlagList = function parseFlagList(flagList) {
};

ConnectionConfig.parseUrl = function(url) {
url = urlParse(url, true);
url = (typeof URL == 'function' && typeof URL.prototype == 'object' ? new URL(url) : urlParse(url, true));

var options = {
host : url.hostname,
port : url.port,
database : url.pathname.substr(1)
};

if (url.auth) {
if (typeof url.username == 'string') {
options.user = url.username;
options.password = decodeUriComponent(url.password);
} else if (url.auth) {
var auth = url.auth.split(':');
options.user = auth.shift();
options.password = auth.join(':');
}

if (url.query) {
if (url.searchParams) {
url.searchParams.forEach(function (value, key) {
try {
// Try to parse this as a JSON expression first
options[key] = JSON.parse(value);
} catch (err) {
// Otherwise assume it is a plain string
options[key] = value;
}
});
} else if (url.query) {
for (var key in url.query) {
var value = url.query[key];

Expand All @@ -207,3 +220,13 @@ ConnectionConfig.parseUrl = function(url) {

return options;
};

function decodeUriComponent(str) {
return str.replace(/\%([a-f0-9]{2})/ig, function (_, hex) {
try {
return String.fromCharCode(parseInt(hex, 16));
} catch (e) {
return _;
}
});
}