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

url: extend URLSearchParams constructor #11060

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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
121 changes: 118 additions & 3 deletions doc/api/url.md
Expand Up @@ -525,7 +525,8 @@ value returned is equivalent to that of `url.href`.
### Class: URLSearchParams

The `URLSearchParams` object provides read and write access to the query of a
`URL`.
`URL`. It can also be used standalone with one of the four following
constructors.
Copy link
Member

Choose a reason for hiding this comment

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

Not a fan of starting a sentence with "It can..."... perhaps something like:

The object can also be used standalone...


```js
const URL = require('url').URL;
Expand All @@ -543,9 +544,121 @@ console.log(myURL.href);
// Prints https://example.org/?a=b
```

#### Constructor: new URLSearchParams([init])
#### Constructor: new URLSearchParams()

* `init` {String} The URL query
Instantiate a new empty `URLSearchParams` object.

#### Constructor: new URLSearchParams(string)

* `string` {String} A query string

Parse the `string` as a query string, and use it to instantiate a new
`URLSearchParams` object. A leading `'?'`, if present, is ignored.

```js
const { URLSearchParams } = require('url');
let params;

params = new URLSearchParams('user=abc&query=xyz');
console.log(params.get('user'));
// Prints 'abc'
console.log(params.toString());
// Prints 'user=abc&query=xyz'

params = new URLSearchParams('?user=abc&query=xyz');
console.log(params.toString());
// Prints 'user=abc&query=xyz'
```

#### Constructor: new URLSearchParams(obj)

* `obj` {Object} An object representing a collection of key-value pairs

Instantiate a new `URLSearchParams` object with a query hash map. The key and
value of each property of `obj` are always coerced to strings.

Warning: Unlike [`querystring`][] module, duplicate keys in the form of array
Copy link
Member

Choose a reason for hiding this comment

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

s/^Warning:/^*Note*:/

values are not allowed. Arrays are stringified using [`array.toString()`][],
which simply joins all array elements with commas.

```js
const { URLSearchParams } = require('url');
const params = new URLSearchParams({
user: 'abc',
query: ['first', 'second']
});
console.log(params.getAll('query'));
// Prints ['first,second']
console.log(params.toString());
// Prints 'user=abc&query=first%2Csecond'
```

#### Constructor: new URLSearchParams(iterable)

* `iterable` {Iterable} An iterable object whose elements are key-value pairs

Instantiate a new `URLSearchParams` object with an iterable map in a way that
is similar to [`Map`][]'s constructor. `iterable` can be an Array or any
iterable object. Elements of `iterable` are key-value pairs, and can themselves
be any iterable object.

Duplicate keys are allowed.

```js
const { URLSearchParams } = require('url');
let params;

// Using an array
params = new URLSearchParams([
['user', 'abc'],
['query', 'first'],
['query', 'second']
]);
console.log(params.toString());
// Prints 'user=abc&query=first&query=second'

// Using a Map object
const map = new Map();
map.set('user', 'abc');
map.set('query', 'xyz');
params = new URLSearchParams(map);
console.log(params.toString());
// Prints 'user=abc&query=xyz'

// Using a generator function
function* getQueryPairs() {
yield ['user', 'abc'];
yield ['query', 'first'];
yield ['query', 'second'];
}
params = new URLSearchParams(getQueryPairs());
console.log(params.toString());
// Prints 'user=abc&query=first&query=second'

// Using a generator function for key-value pairs
function* getSingleQueryPair(idx) {
if (idx === 0) {
yield 'user'; yield 'abc';
} else if (idx === 1) {
yield 'query'; yield 'first';
} else {
yield 'query'; yield 'second';
}
}
params = new URLSearchParams([
getSingleQueryPair(0),
getSingleQueryPair(1),
getSingleQueryPair(2)
]);
console.log(params.toString());
// Prints 'user=abc&query=first&query=second'
Copy link
Member

Choose a reason for hiding this comment

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

The generator examples are good but I would guess that most people probably won’t be interested in that… how about wrapping it in a <details> tag? Does that work?

Copy link
Member Author

Choose a reason for hiding this comment

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

@addaleax, if that is the case I'd rather just remove it. I agree the second generator example is a bit obscure, and it is in fact only compatible with URLSearchParams, not with Map (referenced earlier). Though the first example does seem useful to me.

Copy link
Member

Choose a reason for hiding this comment

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

I’m fine with any of those options… maybe somebody else has a stronger opinion but otherwise just go with whatever you prefer.

Copy link
Member

Choose a reason for hiding this comment

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

Yeah I kinda can't get the merit of the second generator example at first glance. Maybe we can leave that later with a better use case as an example?

Copy link
Member Author

Choose a reason for hiding this comment

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

@joyeecheung, fair.


// Each key-value pair must have exactly two elements
new URLSearchParams([
['user', 'abc', 'error']
]);
// Throws TypeError: Each query pair must be a name/value tuple
```

#### urlSearchParams.append(name, value)

Expand Down Expand Up @@ -712,3 +825,5 @@ console.log(myURL.origin);
[`url.parse()`]: #url_url_parse_urlstring_parsequerystring_slashesdenotehost
[`url.format()`]: #url_url_format_urlobject
[Punycode]: https://tools.ietf.org/html/rfc5891#section-4.4
[`Map`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
[`array.toString()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString
45 changes: 42 additions & 3 deletions lib/internal/url.js
Expand Up @@ -649,10 +649,49 @@ function getObjectFromParams(array) {

class URLSearchParams {
constructor(init = '') {
if (init instanceof URLSearchParams) {
const childParams = init[searchParams];
this[searchParams] = childParams.slice();
if (init === null || init === undefined) {
Copy link
Member

Choose a reason for hiding this comment

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

If we have init = '' as default then init can't be undefined?

Copy link
Member Author

Choose a reason for hiding this comment

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

The user can do new URLSearchParams(undefined). The default is there to echo the = "" in the spec, though now I agree it's a bit pointless.

// record<USVString, USVString>
Copy link
Member

Choose a reason for hiding this comment

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

This comment can be removed I believe.

Copy link
Member Author

Choose a reason for hiding this comment

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

Fixed.

this[searchParams] = [];
} else if (typeof init === 'object') {
const method = init[Symbol.iterator];
if (method === this[Symbol.iterator]) {
// While the spec does not have this branch, we can use it as a
// shortcut to avoid having to go through the costly generic iterator.
const childParams = init[searchParams];
this[searchParams] = childParams.slice();
} else if (method !== null && method !== undefined) {
if (typeof method !== 'function') {
throw new TypeError('Query pairs must be iterable');
}

// sequence<sequence<USVString>>
// Note: per spec we have to first exhaust the lists then process them
const pairs = [];
for (const pair of init) {
if (typeof pair !== 'object' ||
typeof pair[Symbol.iterator] !== 'function') {
throw new TypeError('Each query pair must be iterable');
}
pairs.push(Array.from(pair));
}

this[searchParams] = [];
for (const pair of pairs) {
if (pair.length !== 2) {
throw new TypeError('Each query pair must be a name/value tuple');
}
this[searchParams].push(String(pair[0]), String(pair[1]));
}
} else {
// record<USVString, USVString>
this[searchParams] = [];
for (const key of Object.keys(init)) {
const value = String(init[key]);
this[searchParams].push(key, value);
}
}
} else {
// USVString
init = String(init);
if (init[0] === '?') init = init.slice(1);
initSearchParams(this, init);
Expand Down
78 changes: 68 additions & 10 deletions test/parallel/test-whatwg-url-searchparams-constructor.js
Expand Up @@ -16,23 +16,24 @@ assert.strictEqual(params + '', 'a=b');
params = new URLSearchParams(params);
assert.strictEqual(params + '', 'a=b');

// URLSearchParams constructor, empty.
// URLSearchParams constructor, no arguments
params = new URLSearchParams();
Copy link
Member

Choose a reason for hiding this comment

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

Do we have new URLSearchParams(null) test?

Copy link
Member Author

Choose a reason for hiding this comment

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

Not yet, nor do we have a new URLSearchParams(undefined) test. Both are added.

assert.strictEqual(params.toString(), '');

assert.throws(() => URLSearchParams(), TypeError,
'Calling \'URLSearchParams\' without \'new\' should throw.');
// assert.throws(() => new URLSearchParams(DOMException.prototype), TypeError);
assert.throws(() => {
new URLSearchParams({
toString() { throw new TypeError('Illegal invocation'); }
});
}, TypeError);

// URLSearchParams constructor, empty string as argument
params = new URLSearchParams('');
assert.notStrictEqual(params, null, 'constructor returned non-null value.');
// eslint-disable-next-line no-restricted-properties
assert.notEqual(params, null, 'constructor returned non-null value.');
// eslint-disable-next-line no-proto
assert.strictEqual(params.__proto__, URLSearchParams.prototype,
'expected URLSearchParams.prototype as prototype.');

// URLSearchParams constructor, {} as argument
params = new URLSearchParams({});
// assert.strictEqual(params + '', '%5Bobject+Object%5D=');
assert.strictEqual(params + '', '%5Bobject%20Object%5D=');
assert.strictEqual(params + '', '');

// URLSearchParams constructor, string.
params = new URLSearchParams('a=b');
Expand Down Expand Up @@ -128,3 +129,60 @@ params = new URLSearchParams('a=b%f0%9f%92%a9c');
assert.strictEqual(params.get('a'), 'b\uD83D\uDCA9c');
params = new URLSearchParams('a%f0%9f%92%a9b=c');
assert.strictEqual(params.get('a\uD83D\uDCA9b'), 'c');

// Constructor with sequence of sequences of strings
params = new URLSearchParams([]);
// eslint-disable-next-line no-restricted-properties
assert.notEqual(params, null, 'constructor returned non-null value.');
params = new URLSearchParams([['a', 'b'], ['c', 'd']]);
assert.strictEqual(params.get('a'), 'b');
assert.strictEqual(params.get('c'), 'd');
assert.throws(() => new URLSearchParams([[1]]),
/^TypeError: Each query pair must be a name\/value tuple$/);
assert.throws(() => new URLSearchParams([[1, 2, 3]]),
/^TypeError: Each query pair must be a name\/value tuple$/);

[
// Further confirmation needed
// https://github.com/w3c/web-platform-tests/pull/4523#discussion_r98337513
// {
// input: {'+': '%C2'},
// output: [[' ', '\uFFFD']],
// name: 'object with +'
// },
{
input: {c: 'x', a: '?'},
output: [['c', 'x'], ['a', '?']],
name: 'object with two keys'
},
{
input: [['c', 'x'], ['a', '?']],
output: [['c', 'x'], ['a', '?']],
name: 'array with two keys'
}
].forEach((val) => {
const params = new URLSearchParams(val.input);
let i = 0;
for (const param of params) {
assert.deepStrictEqual(param, val.output[i],
Copy link
Member

Choose a reason for hiding this comment

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

How about assert.deepStrictEqual(Array.from(params), val.output, ...)?

Copy link
Member Author

Choose a reason for hiding this comment

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

Good idea. Fixed also.

`Construct with ${val.name}`);
i++;
}
});

// Custom [Symbol.iterator]
params = new URLSearchParams();
params[Symbol.iterator] = function *() {
yield ['a', 'b'];
};
const params2 = new URLSearchParams(params);
assert.strictEqual(params2.get('a'), 'b');

assert.throws(() => new URLSearchParams({ [Symbol.iterator]: 42 }),
/^TypeError: Query pairs must be iterable$/);
assert.throws(() => new URLSearchParams([{}]),
/^TypeError: Each query pair must be iterable$/);
assert.throws(() => new URLSearchParams(['a']),
/^TypeError: Each query pair must be iterable$/);
assert.throws(() => new URLSearchParams([{ [Symbol.iterator]: 42 }]),
/^TypeError: Each query pair must be iterable$/);
2 changes: 2 additions & 0 deletions tools/doc/type-parser.js
Expand Up @@ -36,6 +36,8 @@ const typeMap = {
'http.IncomingMessage': 'http.html#http_class_http_incomingmessage',
'http.Server': 'http.html#http_class_http_server',
'http.ServerResponse': 'http.html#http_class_http_serverresponse',
'Iterable': jsDocPrefix +
'Reference/Iteration_protocols#The_iterable_protocol',
'Iterator': jsDocPrefix +
'Reference/Iteration_protocols#The_iterator_protocol'
};
Expand Down