Skip to content

Commit

Permalink
parameter encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
alexanderkirtzel committed Jul 18, 2024
1 parent 4408238 commit 8beb7bf
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
3 changes: 2 additions & 1 deletion packages/utils/src/__tests__/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { requestToData, requestToParameter } from '../core';

describe('request', () => {
const str =
'a=z&b=0&c=1&d=true&e=false&f=&g=undefined&h=1.1&i%5B0%5D=1&i%5B1%5D=2&j%5Bx%5D=1&j%5By%5D=2';
'a=z&b=0&c=1&d=true&e=false&f=&g=undefined&h=1.1&i%5B0%5D=1&i%5B1%5D=2&j%5Bx%5D=1&j%5By%5D=2&k=en%20coded';

const obj = {
a: 'z',
Expand All @@ -15,6 +15,7 @@ describe('request', () => {
h: 1.1,
i: [1, 2],
j: { x: 1, y: 2 },
k: 'en coded',
};

test('requestToData', async () => {
Expand Down
9 changes: 5 additions & 4 deletions packages/utils/src/core/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ export function requestToParameter(
): string {
if (!data) return '';

const params = new URLSearchParams();
const params: string[] = [];
const encode = encodeURIComponent;

function addParam(key: string, value: unknown) {
if (value === undefined || value === null) return;
Expand All @@ -62,15 +63,15 @@ export function requestToParameter(
addParam(`${key}[${subKey}]`, subValue),
);
} else {
params.append(key, String(value));
params.push(`${encode(key)}=${encode(String(value))}`);
}
}

if (typeof data === 'object') {
Object.entries(data).forEach(([key, value]) => addParam(key, value));
} else {
return String(data);
return encode(data);
}

return params.toString();
return params.join('&');
}

0 comments on commit 8beb7bf

Please sign in to comment.