url: simplify and improve url formatting by anonrig · Pull Request #46736 · nodejs/node · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 13 additions & 85 deletions lib/internal/url.js
46 changes: 38 additions & 8 deletions lib/url.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
'use strict';

const {
Boolean,
Int8Array,
ObjectKeys,
SafeSet,
Expand All @@ -37,7 +38,10 @@ const {
ERR_INVALID_ARG_TYPE,
ERR_INVALID_URL,
} = require('internal/errors').codes;
const { validateString } = require('internal/validators');
const {
validateString,
validateObject,
} = require('internal/validators');

// This ensures setURLConstructor() is called before the native
// URL::ToObject() method is used.
Expand All @@ -50,11 +54,14 @@ const {
domainToASCII,
domainToUnicode,
fileURLToPath,
formatSymbol,
pathToFileURL,
urlToHttpOptions,
} = require('internal/url');

const {
formatUrl,
} = internalBinding('url');

// Original url.parse() API

function Url() {
Expand Down Expand Up @@ -587,13 +594,36 @@ function urlFormat(urlObject, options) {
} else if (typeof urlObject !== 'object' || urlObject === null) {
throw new ERR_INVALID_ARG_TYPE('urlObject',
['Object', 'string'], urlObject);
} else if (!(urlObject instanceof Url)) {
const format = urlObject[formatSymbol];
return format ?
format.call(urlObject, options) :
Url.prototype.format.call(urlObject);
} else if (urlObject instanceof URL) {
let fragment = true;
let unicode = false;
let search = true;
let auth = true;

if (options) {
validateObject(options, 'options');

if (options.fragment != null) {
fragment = Boolean(options.fragment);
}

if (options.unicode != null) {
unicode = Boolean(options.unicode);
}

if (options.search != null) {
search = Boolean(options.search);
}

if (options.auth != null) {
auth = Boolean(options.auth);
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Setting these up as a set of bit flags may be a bit nicer.

e.g. something like

let flags = 0;
if (options.fragment != null) flags |= kFragment;
if (options.unicode != null) flags |= kUnicode;
// ...

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That does not cover passing { auth: 1 } as options, and still requires Boolean(). I'm not personally in favor of this solution.

}

return formatUrl(urlObject.href, fragment, unicode, search, auth);
}
return urlObject.format();

return Url.prototype.format.call(urlObject);
}

// These characters do not need escaping:
Expand Down
73 changes: 59 additions & 14 deletions src/node_url.cc
Loading