Skip to content

Commit

Permalink
Use qs in getUrlWithQuery()
Browse files Browse the repository at this point in the history
  • Loading branch information
atas committed Oct 20, 2024
1 parent 2fadc78 commit 3c62929
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 20 deletions.
30 changes: 15 additions & 15 deletions src/utils/__tests__/urlUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,21 @@ describe('getUrlWithQuery', () => {
const url = 'https://example.com';
const query = { foo: 'bar', baz: 'qux' };
const result = getUrlWithQuery(url, query);
expect(result).toBe('https://example.com/?foo=bar&baz=qux');
expect(result).toBe('https://example.com/?baz=qux&foo=bar');
});

test('should add query parameters to the URL', () => {
const url = '/';
const query = { foo: 'bar', baz: 'qux' };
const result = getUrlWithQuery(url, query);
expect(result).toBe('/?baz=qux&foo=bar');
});

test('should overwrite existing query parameters', () => {
const url = 'https://example.com?foo=old';
const url = '';
const query = { foo: 'new', baz: 'qux' };
const result = getUrlWithQuery(url, query);
expect(result).toBe('https://example.com/?foo=new&baz=qux');
expect(result).toBe('/?baz=qux&foo=new');
});

test('should handle empty query object', () => {
Expand All @@ -53,23 +60,16 @@ describe('getUrlWithQuery', () => {
});

test('should handle URL with existing query parameters', () => {
const url = 'https://example.com?existing=param';
const url = '/';
const query = { foo: 'bar' };
const result = getUrlWithQuery(url, query);
expect(result).toBe('https://example.com/?existing=param&foo=bar');
});

test('should handle special characters in query parameters', () => {
const url = 'https://example.com';
const query = { 'foo bar': 'baz qux' };
const result = getUrlWithQuery(url, query);
expect(result).toBe('https://example.com/?foo+bar=baz+qux');
expect(result).toBe('/?foo=bar');
});

test('should ignore nulls', () => {
const url = 'https://example.com';
const url = '/';
const query = { 'foo': null, 'bar': undefined };
const result = getUrlWithQuery(url, query);
expect(result).toBe('https://example.com/');
expect(result).toBe('/');
});
});
13 changes: 8 additions & 5 deletions src/utils/urlUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,12 @@ export function isHttpsUrl(url: string) {
}

export function getUrlWithQuery(url: string, query: { [key: string]: any }) {
const urlObj = new URL(url);
Object.keys(query).filter(k => query[k]).forEach(key => {
urlObj.searchParams.set(key, query[key]);
});
return urlObj.toString();
let q = qs.stringify(query, {skipNull: true, skipEmptyString: true});
q = q ? `?${q}` : '';

if (!url.endsWith('/')) {
url += '/';
}

return url + q;
}

0 comments on commit 3c62929

Please sign in to comment.