Created
February 1, 2021 13:43
-
-
Save skulptur/ea7b80a207b48cc635d64afdbc5e80ba to your computer and use it in GitHub Desktop.
Util for replacing params in a React router style url config
This file contains hidden or 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
/** | |
* Builds a path from a template and replaces the params | |
* | |
* @function createPath | |
* @param path The configured path (e.g. /foo/:bar) | |
* @param params The param values you want to replace it with (e.g. \{bar: 'baz'\}) | |
* @param search Any query string values that you want to add | |
* @category routing | |
*/ | |
export const createPath = ( | |
path: string, | |
params: { [key: string]: string } = {}, | |
search: string = '', | |
) => | |
path | |
// first replace all params | |
.replace(/:(\w+)/g, (match, param) => { | |
if (typeof params[param] !== 'undefined') { | |
return params[param] || ''; | |
} | |
return match; | |
}) | |
// remove unresolved optional parts | |
.replace(/\/:(\w+)\?/g, () => '') | |
// remove ? from resolved optional parts | |
.replace(/([^:]+?)\?/g, (match, part) => part) | |
// do we still have params left? | |
.replace(/:(\w+)/g, (match, param) => { | |
throw new Error(`Param "${param}" is missing in params ${params}, needed for '${path}'`); | |
}) + search; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment