Skip to content

Commit

Permalink
fix: Encode URI components in serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
neet committed Nov 25, 2022
1 parent ebdaee8 commit 8a2be08
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
8 changes: 8 additions & 0 deletions src/serializers/rails-querystring.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ describe('railsQueryString', () => {
expect(result).toBe('key1=value1&key2=value2');
});

it('encodes string safely', () => {
const result = railsQueryString.stringify({
q: 'https://neet.love',
});
// cspell:disable-next-line
expect(result).toBe('q=https%3A%2F%2Fneet.love');
});

it('encodes an array inside a record', () => {
const result = railsQueryString.stringify({
key1: 'value1',
Expand Down
12 changes: 8 additions & 4 deletions src/serializers/rails-querystring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,17 @@ const stringify = (object?: unknown): string => {
const values = Object.entries(object)
.reduce<string[]>((prev, [k, v]) => {
if (Array.isArray(v)) {
const xs = v.map((x) => `${k}[]=${x}`);
const xs = v.map((x) => `${k}[]=${encodeURIComponent(x)}`);
return [...prev, ...xs];
}
if (isObject(v)) {
throw new TypeError('Encoding nested object is not supported');
if (
typeof v === 'string' ||
typeof v === 'number' ||
typeof v === 'boolean'
) {
return [...prev, `${k}=${encodeURIComponent(v)}`];
}
return [...prev, `${k}=${v}`];
throw new TypeError('Encoding nested object is not supported');
}, [])
.join('&');

Expand Down

0 comments on commit 8a2be08

Please sign in to comment.