Skip to content

Commit

Permalink
getUrlWithQuery()
Browse files Browse the repository at this point in the history
  • Loading branch information
atas committed Oct 20, 2024
1 parent 09aded1 commit 2fadc78
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
46 changes: 45 additions & 1 deletion src/utils/__tests__/urlUtils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { convertToSlug } from '../urlUtils';
import { convertToSlug, getUrlWithQuery } from '../urlUtils';

describe('convertToSlug', () => {
test('should return null for null input', () => {
Expand Down Expand Up @@ -29,3 +29,47 @@ describe('convertToSlug', () => {
expect(convertToSlug(' Hello World! 123 ')).toBe('hello-world-123');
});
});

describe('getUrlWithQuery', () => {
test('should add query parameters to the URL', () => {
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');
});

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

test('should handle empty query object', () => {
const url = 'https://example.com';
const query = {};
const result = getUrlWithQuery(url, query);
expect(result).toBe('https://example.com/');
});

test('should handle URL with existing query parameters', () => {
const url = 'https://example.com?existing=param';
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');
});

test('should ignore nulls', () => {
const url = 'https://example.com';
const query = { 'foo': null, 'bar': undefined };
const result = getUrlWithQuery(url, query);
expect(result).toBe('https://example.com/');
});
});
8 changes: 8 additions & 0 deletions src/utils/urlUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,11 @@ export function isHttpsUrl(url: string) {
/^https:\/\/[a-zAz0-9-]+(\.[a-zA-Z0-9-]+)*(\:[0-9]+)?(\/[^?\s]*)?(\?[^#\s]*)?(#[^\s]*)?$/;
return typeof url === 'string' && regex.test(url);
}

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();
}

0 comments on commit 2fadc78

Please sign in to comment.