Skip to content

Instantly share code, notes, and snippets.

@DimitryDushkin
Last active March 21, 2017 08:58
Show Gist options
  • Save DimitryDushkin/c9ec7d7c934f3e00515567985fe3a2d7 to your computer and use it in GitHub Desktop.
Save DimitryDushkin/c9ec7d7c934f3e00515567985fe3a2d7 to your computer and use it in GitHub Desktop.
Simple and safe code for converting express-style paths to URLs
/**
*
* @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