-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #46 from behzadam/42-add-url-utility-functions
42 add url utility functions
- Loading branch information
Showing
2 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/** | ||
* Returns key/value pairs of the given url with params. | ||
* Also, check out this {@link https://github.com/steven-tey/dub/blob/main/lib/utils.ts#L330C20 | link}. | ||
* | ||
* @param url - the given url | ||
* @returns key/value pairs of param and value, or an empty object | ||
* @example | ||
* ```ts | ||
* const params = getParamsFromURL('https://example.org/?a=1&b=2&c=3') | ||
* // { a: '1', b: '2', c: '3' } | ||
* ``` | ||
* | ||
* @public | ||
*/ | ||
export function getParamsFromURL(url: string): Record<string, string> { | ||
if (!url) return {}; | ||
try { | ||
const params = new URL(url).searchParams; | ||
const paramsObj: Record<string, string> = {}; | ||
for (const [key, value] of params.entries()) { | ||
if (value && value !== '') { | ||
paramsObj[key] = value; | ||
} | ||
} | ||
return paramsObj; | ||
} catch (e) { | ||
return {}; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import { getParamsFromURL } from './get-params-from-url'; | ||
|
||
describe('getParamsFromURL', () => { | ||
test.each` | ||
input | expected | ||
${'https://example.org/?a=1&b=2&c=3'} | ${{ a: '1', b: '2', c: '3' }} | ||
${'https://example.org/?t=Salz+%26+Pfeffer'} | ${{ t: 'Salz & Pfeffer' }} | ||
${'https://example.org/'} | ${{}} | ||
`('returns $expected when input is: $input', ({ input, expected }) => { | ||
expect(getParamsFromURL(input)).toStrictEqual(expected); | ||
}); | ||
}); |