mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
Implementation of URLSearchParams Methods (#50043)
Summary: This PR addresses the following issues and enhances the functionality of `URLSearchParams`: 1. Extended Initialization Parameters: Previously, only `Record<string, string>` was supported while initialising URLSearchParams. Now supports `string`, `Record<string, string>`, and `Array<[string, string]>` (aligning with web standards). 2. Added Implementation for `delete()`, `get()`, `getAll()`, `has()`, `sort()`, and `set()`. 3. Addition of Iteration Methods: Added `keys()`, `values()`, `entries()`, and `forEach()` methods. Outputs are identical to web. 4. Bug Fix: Incorrect Initialization from URL. Previously, `URLSearchParams` was initialized with an empty value when accessed via `url.searchParams`, even if the `URL` contained search parameters. ## Changelog: [General][Added] Implementation for URLSearchParams Pull Request resolved: https://github.com/facebook/react-native/pull/50043 Test Plan: Can be tested by below code ```js const isHermes = () => !!global.HermesInternal; const params = new URLSearchParams(""); console.log("Is Hermes Enabled:-",isHermes()) console.log("Values:", Array.from(params.values())); // ✅ ["value1", "value2"] console.log("Keys:", Array.from(params.keys())); // ✅ ["key1", "key2"] console.log("Entries:", Array.from(params.entries())); // ✅ [["key1", "value1"], ["key2", "value2"]] params.forEach((value, key) => { console.log(`${key}: ${value}`); }); console.log("Has 'key1'", params.has("key1")); // ✅ true console.log("Has 'key3'", params.has("key3")); // ✅ false console.log("Get 'key1':", params.get("key1")); // ✅ "value1" console.log("Get 'key3':", params.get("key3")); // ✅ null ``` Tested on both hermes and JSC. Hermes:-  JSC:-  Reviewed By: cipolleschi Differential Revision: D71965101 Pulled By: huntie fbshipit-source-id: c0a0f965ac1ff9577cdc8b3c11f0dd0ced538868
This commit is contained in:
1 parent
aadb1f1116
commit
af1f1e4fe5
6 files changed
+208
-46
No files matched your search
+1
-1
@@ -160,7 +160,7 @@ export class URL {
|
||||
|
||||
get searchParams(): URLSearchParams {
|
||||
if (this._searchParamsInstance == null) {
|
||||
this._searchParamsInstance = new URLSearchParams();
|
||||
this._searchParamsInstance = new URLSearchParams(this.search);
|
||||
}
|
||||
return this._searchParamsInstance;
|
||||
}
|
||||
|
||||
+106
-31
@@ -11,60 +11,135 @@
|
||||
// Small subset from whatwg-url: https://github.com/jsdom/whatwg-url/tree/master/src
|
||||
// The reference code bloat comes from Unicode issues with URLs, so those won't work here.
|
||||
export class URLSearchParams {
|
||||
_searchParams: Array<[string, string]> = [];
|
||||
_searchParams: Map<string, string[]> = new Map();
|
||||
|
||||
constructor(params?: Record<string, string>) {
|
||||
if (typeof params === 'object') {
|
||||
Object.keys(params).forEach(key => this.append(key, params[key]));
|
||||
constructor(params?: Record<string, string> | string | [string, string][]) {
|
||||
if (params === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof params === 'string') {
|
||||
// URLSearchParams("key1=value1&key2=value2");
|
||||
params
|
||||
.replace(/^\?/, '')
|
||||
.split('&')
|
||||
.forEach(pair => {
|
||||
if (!pair) {
|
||||
return;
|
||||
}
|
||||
const [key, value] = pair
|
||||
.split('=')
|
||||
.map(part => decodeURIComponent(part.replace(/\+/g, ' ')));
|
||||
this.append(key, value);
|
||||
});
|
||||
} else if (Array.isArray(params)) {
|
||||
//URLSearchParams([["key1", "value1"], ["key2", "value2"]]);
|
||||
params.forEach(([key, value]) => this.append(key, value));
|
||||
} else if (typeof params === 'object') {
|
||||
//URLSearchParams({ key1: "value1", key2: "value2" });
|
||||
Object.entries(params).forEach(([key, value]) => this.append(key, value));
|
||||
}
|
||||
}
|
||||
|
||||
append(key: string, value: string): void {
|
||||
this._searchParams.push([key, value]);
|
||||
if (!this._searchParams.has(key)) {
|
||||
this._searchParams.set(key, [value]); // Initialize with an array if key is missing
|
||||
} else {
|
||||
this._searchParams.get(key)?.push(value); // Else push the value to the array
|
||||
}
|
||||
}
|
||||
|
||||
delete(name: string): empty {
|
||||
throw new Error('URLSearchParams.delete is not implemented');
|
||||
delete(name: string): void {
|
||||
this._searchParams.delete(name);
|
||||
}
|
||||
|
||||
get(name: string): empty {
|
||||
throw new Error('URLSearchParams.get is not implemented');
|
||||
get(name: string): string | null {
|
||||
const values = this._searchParams.get(name);
|
||||
return values ? values[0] : null;
|
||||
}
|
||||
|
||||
getAll(name: string): empty {
|
||||
throw new Error('URLSearchParams.getAll is not implemented');
|
||||
getAll(name: string): string[] {
|
||||
return this._searchParams.get(name) ?? [];
|
||||
}
|
||||
|
||||
has(name: string): empty {
|
||||
throw new Error('URLSearchParams.has is not implemented');
|
||||
has(name: string): boolean {
|
||||
return this._searchParams.has(name);
|
||||
}
|
||||
|
||||
set(name: string, value: string): empty {
|
||||
throw new Error('URLSearchParams.set is not implemented');
|
||||
set(name: string, value: string): void {
|
||||
this._searchParams.set(name, [value]);
|
||||
}
|
||||
|
||||
sort(): empty {
|
||||
throw new Error('URLSearchParams.sort is not implemented');
|
||||
keys(): Iterator<string> {
|
||||
return this._searchParams.keys();
|
||||
}
|
||||
|
||||
values(): Iterator<string> {
|
||||
function* generateValues(params: Map<string, string[]>): Iterator<string> {
|
||||
for (const valueArray of params.values()) {
|
||||
for (const value of valueArray) {
|
||||
yield value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return generateValues(this._searchParams);
|
||||
}
|
||||
|
||||
entries(): Iterator<[string, string]> {
|
||||
function* generateEntries(
|
||||
params: Map<string, string[]>,
|
||||
): Iterator<[string, string]> {
|
||||
for (const [key, values] of params) {
|
||||
for (const value of values) {
|
||||
yield [key, value];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return generateEntries(this._searchParams);
|
||||
}
|
||||
|
||||
forEach(
|
||||
callback: (value: string, key: string, searchParams: this) => void,
|
||||
): void {
|
||||
for (const [key, values] of this._searchParams) {
|
||||
for (const value of values) {
|
||||
callback(value, key, this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort(): void {
|
||||
this._searchParams = new Map(
|
||||
[...this._searchParams.entries()].sort(([a], [b]) => a.localeCompare(b)),
|
||||
);
|
||||
}
|
||||
|
||||
// $FlowFixMe[unsupported-syntax]
|
||||
[Symbol.iterator](): Iterator<[string, string]> {
|
||||
return this._searchParams[Symbol.iterator]();
|
||||
const entries: [string, string][] = [];
|
||||
|
||||
for (const [key, values] of this._searchParams) {
|
||||
for (const value of values) {
|
||||
entries.push([key, value]);
|
||||
}
|
||||
}
|
||||
|
||||
return entries[Symbol.iterator]();
|
||||
}
|
||||
|
||||
toString(): string {
|
||||
if (this._searchParams.length === 0) {
|
||||
return '';
|
||||
}
|
||||
const last = this._searchParams.length - 1;
|
||||
return this._searchParams.reduce((acc, curr, index) => {
|
||||
return (
|
||||
acc +
|
||||
encodeURIComponent(curr[0]) +
|
||||
'=' +
|
||||
encodeURIComponent(curr[1]) +
|
||||
(index === last ? '' : '&')
|
||||
);
|
||||
}, '');
|
||||
return Array.from(this._searchParams.entries())
|
||||
.map(([key, values]) =>
|
||||
values
|
||||
.map(
|
||||
value =>
|
||||
`${encodeURIComponent(key).replace(/%20/g, '+')}=${encodeURIComponent(
|
||||
value,
|
||||
).replace(/%20/g, '+')}`, // Convert only spaces to '+'
|
||||
)
|
||||
.join('&'),
|
||||
)
|
||||
.join('&');
|
||||
}
|
||||
}
|
||||
@@ -10,14 +10,19 @@
|
||||
|
||||
declare export class URLSearchParams {
|
||||
_searchParams: Array<[string, string]>;
|
||||
constructor(params?: Record<string, string>): void;
|
||||
constructor(
|
||||
params?: Record<string, string> | string | Array<[string, string]>,
|
||||
): void;
|
||||
append(key: string, value: string): void;
|
||||
delete(name: string): empty;
|
||||
get(name: string): empty;
|
||||
getAll(name: string): empty;
|
||||
has(name: string): empty;
|
||||
set(name: string, value: string): empty;
|
||||
sort(): empty;
|
||||
delete(name: string): void;
|
||||
get(name: string): string;
|
||||
getAll(name: string): Array<string>;
|
||||
has(name: string): boolean;
|
||||
set(name: string, value: string): void;
|
||||
sort(): void;
|
||||
@@iterator(): Iterator<[string, string]>;
|
||||
toString(): string;
|
||||
keys(): Iterator<string>;
|
||||
values(): Iterator<string>;
|
||||
entries(): Iterator<[string, string]>;
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
'use strict';
|
||||
|
||||
const URL = require('../URL').URL;
|
||||
const URLSearchParams = require('../URL').URLSearchParams;
|
||||
|
||||
describe('URL', function () {
|
||||
it('should pass Mozilla Dev Network examples', () => {
|
||||
@@ -52,5 +53,80 @@ describe('URL', function () {
|
||||
expect(url.pathname).toBe('/docs/path');
|
||||
expect(url.port).toBe('8080');
|
||||
expect(url.search).toBe('?query=testQuery&key=value');
|
||||
|
||||
// Test searchParams
|
||||
const searchParams = url.searchParams;
|
||||
expect(searchParams.get('query')).toBe('testQuery');
|
||||
expect(searchParams.get('key')).toBe('value');
|
||||
|
||||
const paramsFromString = new URLSearchParams(
|
||||
[
|
||||
'?param1=value1',
|
||||
'¶m2=value2%20with%20spaces',
|
||||
'¶m3=value3+with+spaces+legacy',
|
||||
].join(''),
|
||||
);
|
||||
expect(paramsFromString.get('param1')).toBe('value1');
|
||||
expect(paramsFromString.get('param2')).toBe('value2 with spaces');
|
||||
expect(paramsFromString.get('param3')).toBe('value3 with spaces legacy');
|
||||
expect(paramsFromString.toString()).toBe(
|
||||
'param1=value1¶m2=value2+with+spaces¶m3=value3+with+spaces+legacy',
|
||||
);
|
||||
|
||||
const paramsFromObject = new URLSearchParams({
|
||||
user: 'john',
|
||||
age: '30',
|
||||
active: 'true',
|
||||
});
|
||||
|
||||
expect(paramsFromObject.get('user')).toBe('john');
|
||||
expect(paramsFromObject.get('age')).toBe('30');
|
||||
expect(paramsFromObject.get('active')).toBe('true');
|
||||
|
||||
const valuesArray = Array.from(paramsFromObject.values());
|
||||
expect(valuesArray).toEqual(['john', '30', 'true']);
|
||||
const entriesArray = Array.from(paramsFromObject.entries());
|
||||
expect(entriesArray).toEqual([
|
||||
['user', 'john'],
|
||||
['age', '30'],
|
||||
['active', 'true'],
|
||||
]);
|
||||
|
||||
// URLSearchParams: Empty
|
||||
const emptyParams = new URLSearchParams('');
|
||||
expect([...emptyParams.entries()]).toEqual([]);
|
||||
|
||||
// URLSearchParams: Array (for multiple values of the same key)
|
||||
const paramsFromArray = new URLSearchParams([
|
||||
['key1', 'value1'],
|
||||
['key1', 'value2'],
|
||||
['key2', 'value3'],
|
||||
]);
|
||||
expect(paramsFromArray.getAll('key1')).toEqual(['value1', 'value2']);
|
||||
expect(paramsFromArray.get('key2')).toBe('value3');
|
||||
|
||||
// Manipulating existing search params in the URL
|
||||
const urlParams = url.searchParams;
|
||||
expect(urlParams.get('query')).toBe('testQuery');
|
||||
expect(urlParams.get('key')).toBe('value');
|
||||
|
||||
// Adding a new param
|
||||
urlParams.append('newKey', 'newValue');
|
||||
expect(urlParams.get('newKey')).toBe('newValue');
|
||||
|
||||
// Deleting a param
|
||||
urlParams.delete('key');
|
||||
expect(urlParams.get('key')).toBeNull();
|
||||
|
||||
// Checking if a param exists
|
||||
expect(urlParams.has('query')).toBe(true);
|
||||
expect(urlParams.has('key')).toBe(false);
|
||||
|
||||
// Sorting URLSearchParams
|
||||
const unsortedParams = new URLSearchParams(
|
||||
'?z=last&b=second&c=third&a=first',
|
||||
);
|
||||
unsortedParams.sort();
|
||||
expect(unsortedParams.toString()).toBe('a=first&b=second&c=third&z=last');
|
||||
});
|
||||
});
|
||||
@@ -1345,16 +1345,21 @@ declare export class URL {
|
||||
|
||||
exports[`public API should not change unintentionally Libraries/Blob/URLSearchParams.js.flow 1`] = `
|
||||
"declare export class URLSearchParams {
|
||||
constructor(params?: Record<string, string>): void;
|
||||
constructor(
|
||||
params?: Record<string, string> | string | Array<[string, string]>
|
||||
): void;
|
||||
append(key: string, value: string): void;
|
||||
delete(name: string): empty;
|
||||
get(name: string): empty;
|
||||
getAll(name: string): empty;
|
||||
has(name: string): empty;
|
||||
set(name: string, value: string): empty;
|
||||
sort(): empty;
|
||||
delete(name: string): void;
|
||||
get(name: string): string;
|
||||
getAll(name: string): Array<string>;
|
||||
has(name: string): boolean;
|
||||
set(name: string, value: string): void;
|
||||
sort(): void;
|
||||
@@iterator(): Iterator<[string, string]>;
|
||||
toString(): string;
|
||||
keys(): Iterator<string>;
|
||||
values(): Iterator<string>;
|
||||
entries(): Iterator<[string, string]>;
|
||||
}
|
||||
"
|
||||
`;
|
||||
|
||||
@@ -33,6 +33,7 @@ function URLComponent(props: Props) {
|
||||
<RNTesterText testID="URL-pathname">{`pathname: ${parsedUrl.pathname}`}</RNTesterText>
|
||||
<RNTesterText testID="URL-port">{`port: ${parsedUrl.port}`}</RNTesterText>
|
||||
<RNTesterText testID="URL-search">{`search: ${parsedUrl.search}`}</RNTesterText>
|
||||
<RNTesterText testID="URL-search-params">{`searchParams: ${parsedUrl.searchParams.toString()}`}</RNTesterText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user