Last active
March 21, 2017 08:58
-
-
Save DimitryDushkin/c9ec7d7c934f3e00515567985fe3a2d7 to your computer and use it in GitHub Desktop.
Simple and safe code for converting express-style paths to URLs
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
/** | |
* | |
* @param {String} path - express-style path | |
* @param {Object} params | |
* @returns {String} | |
* | |
* @example pathToUrl('/users/:userId', { userId: 10 }) -> '/users/10' | |
*/ | |
export const pathToUrl = (path, params) => { | |
return path.replace(/:(\w+)/g, (match, str) => { | |
if (!params[str]) { | |
throw new TypeError(`No param for path match "${match}".`); | |
} | |
return params[str]; | |
}); | |
}; | |
// pathToUrl('/lab/sample/:sampleId/analysis/:analysisId', { sampleId: 10, analysisId: 20 }); | |
// -> "/lab/sample/10/analysis/20" | |
// pathToUrl('/users/:userId', { userId: 10 }) | |
// -> '/users/10' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment