!96 [inula-request]<feat> 支持 params 参数中 value 为数组的场景

Merge pull request !96 from 涂旭辉/master
This commit is contained in:
openInula-robot 2023-12-05 11:49:50 +00:00 committed by Gitee
commit 20a17e4663
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
2 changed files with 13 additions and 2 deletions

View File

@ -386,7 +386,18 @@ const convertToCamelCase = (str: string) => {
function objectToQueryString(obj: Record<string, any>) { function objectToQueryString(obj: Record<string, any>) {
return Object.keys(obj) return Object.keys(obj)
.map(key => encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])) .map(key => {
// params 中 value 为数组时需特殊处理,如:{ key: [1, 2, 3] } -> key[]=1&key[]=2&key[]=3
if (Array.isArray(obj[key])) {
let urlPart = '';
obj[key].forEach((value: string) => {
urlPart = `${urlPart}${key}[]=${value}&`;
return urlPart;
});
return urlPart.slice(0, -1);
}
return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]);
})
.join('&'); .join('&');
} }

View File

@ -53,7 +53,7 @@ describe('objectToQueryString function', () => {
key5: { a: 'b' }, key5: { a: 'b' },
}; };
const expectedResult = const expectedResult =
'key1=string&key2=42&key3=true&key4=1%2C2%2C3&key5=%5Bobject%20Object%5D'; 'key1=string&key2=42&key3=true&key4[]=1&key4[]=2&key4[]=3&key5=%5Bobject%20Object%5D';
const result = utils.objectToQueryString(input); const result = utils.objectToQueryString(input);
expect(result).toBe(expectedResult); expect(result).toBe(expectedResult);
}); });