Last active
September 2, 2023 14:28
-
-
Save yurkimus/f1effaa84b8dd9885ebb9493d56f6482 to your computer and use it in GitHub Desktop.
Building URL with filtered URLSearchParameters
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
const url = createUrl.bind(null, 'https://jsonplaceholder.typicode.com') | |
const todosUrl = url('todos', { _limit: 10, _offset: undefined, id: null }) | |
todosUrl.toString() // => 'https://jsonplaceholder.typicode.com/todos?_limit=10' |
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
/** | |
* Clears unwanted search parameters (null, undefined, or empty string) from a given URLSearchParams object. | |
* | |
* @param {URLSearchParams} searchParams - The URLSearchParams object to be cleared. | |
* | |
* @returns {URLSearchParams} - The cleared URLSearchParams object. | |
*/ | |
const clearSearchParams = searchParams => { | |
Array.from(searchParams) | |
.filter( | |
([, value]) => value === '' || value === 'null' || value === 'undefined' | |
) | |
.forEach(([key]) => searchParams.delete(key)) | |
return searchParams | |
} | |
/** | |
* Constructs a URL by combining pathname, search parameters, and base URL, while clearing unwanted search parameters. | |
* | |
* @param {string} pathname - The path portion of the URL. | |
* @param {ConstructorParameters<typeof URLSearchParams>[0]} searchParamsInit - An object containing the search parameters. | |
* @param {string} base - The base URL to be combined with pathname and search parameters. | |
* | |
* @returns {URL} - The constructed URL object. | |
*/ | |
const createUrl = (base, pathname, searchParamsInit) => { | |
const created = new URL(pathname, base) | |
const searchParams = new URLSearchParams(searchParamsInit) | |
created.search = clearSearchParams(searchParams).toString() | |
return created | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment