fix(http): honor RequestArgs.search and RequestArgs.params map type
Currently `new Request({search: ...})` is not honored, and `new Request({params: {'x': 'y'}) doesn't work either, as this object would have toString() called. This change allows both of these cases to work, as proved by the 2 new tests. Fixes #15761 PR Close #16392
This commit is contained in:
parent
547c363473
commit
aef524506b
|
@ -76,8 +76,14 @@ export class Request extends Body {
|
|||
// TODO: assert that url is present
|
||||
const url = requestOptions.url;
|
||||
this.url = requestOptions.url !;
|
||||
if (requestOptions.params) {
|
||||
const params = requestOptions.params.toString();
|
||||
const paramsArg = requestOptions.params || requestOptions.search;
|
||||
if (paramsArg) {
|
||||
let params: string;
|
||||
if (typeof paramsArg === 'object' && !(paramsArg instanceof URLSearchParams)) {
|
||||
params = urlEncodeParams(paramsArg).toString();
|
||||
} else {
|
||||
params = paramsArg.toString();
|
||||
}
|
||||
if (params.length > 0) {
|
||||
let prefix = '?';
|
||||
if (this.url.indexOf('?') != -1) {
|
||||
|
@ -163,6 +169,19 @@ export class Request extends Body {
|
|||
}
|
||||
}
|
||||
|
||||
function urlEncodeParams(params: {[key: string]: any}): URLSearchParams {
|
||||
const searchParams = new URLSearchParams();
|
||||
Object.keys(params).forEach(key => {
|
||||
const value = params[key];
|
||||
if (value && Array.isArray(value)) {
|
||||
value.forEach(element => searchParams.append(key, element.toString()));
|
||||
} else {
|
||||
searchParams.append(key, value.toString());
|
||||
}
|
||||
});
|
||||
return searchParams;
|
||||
}
|
||||
|
||||
const noop = function() {};
|
||||
const w = typeof window == 'object' ? window : noop;
|
||||
const FormData = (w as any /** TODO #9100 */)['FormData'] || noop;
|
||||
|
|
|
@ -109,5 +109,15 @@ export function main() {
|
|||
|
||||
expect(req.text()).toEqual('');
|
||||
});
|
||||
|
||||
it('should use object params', () => {
|
||||
const req = new Request({url: 'http://test.com', params: {'a': 3, 'b': ['x', 'y']}});
|
||||
expect(req.url).toBe('http://test.com?a=3&b=x&b=y');
|
||||
});
|
||||
|
||||
it('should use search if present', () => {
|
||||
const req = new Request({url: 'http://test.com', search: 'a=1&b=2'});
|
||||
expect(req.url).toBe('http://test.com?a=1&b=2');
|
||||
})
|
||||
});
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue