Skip to content

Instantly share code, notes, and snippets.

@kkamkou
Last active Oct 13, 2015
Embed
What would you like to do?
express.js route to url with options replacement
/**
* @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, '');
};
@kkamkou
Copy link
Author

kkamkou commented Dec 21, 2012

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.

var a = {route: {path: '/:test/:me?/:please'}, params: {test: 'hello', please: 'please'}};
var b = {test: 'world', please: 'sure'};

xx.getUrnFromRequest(a, b); // '/world/sure'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment