Last active
October 13, 2015 04:28
-
-
Save kkamkou/4139877 to your computer and use it in GitHub Desktop.
express.js route to url with options replacement
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
/** | |
* @category Library | |
* @package Utilits | |
* @author Kanstantsin A Kamkou (kkamkou@gmail.com) | |
*/ | |
var _ = require('lodash'); | |
/** | |
* Converts route to the url, replacing keys if needed | |
* | |
* @param {Object} request | |
* @param {Object} bindSet | |
* @return {String} | |
*/ | |
module.exports.getUrnFromRequest = function (request, bindSet) { | |
// some validation | |
if (!_.isObject(request) || !_.isPlainObject(bindSet)) { | |
throw new TypeError('"request" and "bindSet" are required'); | |
} | |
// no replacers found | |
if (!_.values(bindSet).length) { | |
return request.path || ''; | |
} | |
// defaults | |
var routePath = request.route.path || '', | |
mask = /(?:\/:?)(\w+)\??/g, | |
bindSet = _.extend(request.params, bindSet), | |
matches, urn = routePath; | |
// translation | |
while ((matches = mask.exec(routePath)) !== null) { | |
if (bindSet[matches[1]]) { | |
urn = urn.replace(matches[0], '/' + bindSet[matches[1]]); | |
} | |
} | |
// some cleanup for optional params | |
return urn.replace(/\/:\w+\?/g, ''); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This function useful for the redirection. Example you task is to change only one variable in the express.js route. Like to just from: /my/cool/site to /my/epic/site with mask: /:owner/:power/site.