Skip to content

Commit

Permalink
bring back server.router.render
Browse files Browse the repository at this point in the history
Took the base code from latest version 6 and applied the version 7 routing.

fixes restify#1684
  • Loading branch information
balexandre committed Sep 11, 2018
1 parent e663699 commit 0de7411
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions lib/router.js
Expand Up @@ -114,6 +114,45 @@ Router.prototype.lookupByName = function lookupByName(name, req, res) {
return route.chain.run.bind(route.chain);
};

/**
* Takes an object of route params and query params, and 'renders' a URL.
*
* @public
* @function render
* @param {String} routeName - the route name
* @param {Object} params - an object of route params
* @param {Object} query - an object of query params
* @returns {String} URL
*/
Router.prototype.render = function render(routeName, params, query) {
var self = this;

function pathItem(match, key) {
if (params.hasOwnProperty(key) === false) {
throw new Error(
'Route <' + routeName + '> is missing parameter <' + key + '>'
);
}
return '/' + encodeURIComponent(params[key]);
}

function queryItem(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(query[key]);
}

var route = self._registry.get()[routeName];

if (!route) {
return null;
}

var _path = route.spec.path;
var _url = _path.replace(/\/:([A-Za-z0-9_]+)(\([^\\]+?\))?/g, pathItem);
var items = Object.keys(query || {}).map(queryItem);
var queryString = items.length > 0 ? '?' + items.join('&') : '';
return _url + queryString;
};

/**
* Adds a route.
*
Expand Down

0 comments on commit 0de7411

Please sign in to comment.