Skip to content

Instantly share code, notes, and snippets.

@naholyr
Created January 22, 2012 18:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naholyr/1657932 to your computer and use it in GitHub Desktop.
Save naholyr/1657932 to your computer and use it in GitHub Desktop.
Writing a "url_for" helper for Express
// What name can I refer to ?
app.get('/hello-world', function () { console.log(3); });
// OK, suppose I can build the path from params
app.get('/:id/:name', function hello1 () { console.log(1); });
// OK, suppose the "callback" is the last one
app.get('/hello/:name', requiresAuthentication, function hello2 () { console.log(2); });
// How do I build the path ?
app.get(/\/hi\/([a-z]+)/, function hello3 () { console.log(3); });
// Expected example
console.log(app.url_for('hello1', {"id": 42, "name": "dude", "p1": 33, "p2": "some additional param"}));
// /42/dude?p1=33&p2=some%20additional%20param
app.url_for = function url_for (route, params) {
params = params || {};
var url = null, url_params = {};
for (var i=0; i<this.routes.routes.get.length; i++) {
var a_route = this.routes.routes.get[i];
var callback = a_route.callbacks[a_route.callbacks.length-1];
if (callback.name === route) {
url = a_route.path;
if (a_route.keys) {
for (var j=0; j<a_route.keys.length; j++) {
var key = a_route.keys[j];
if (!key.optional && 'undefined' === typeof params[key.name]) {
throw new Error('Missing parameter "' + key.name + '" for route "' + route + '"');
}
var value = params[key.name] || null;
if (value !== null) {
url_params[key.name] = value;
}
}
}
break;
}
}
if (url === null) {
url = route;
}
if (!url.match(/^\//)) {
throw new Error('Invalid URL: no trailing slash');
}
for (var missing_param in params) {
if ('undefined' == typeof url_params[missing_param]) {
url_params[missing_param] = params[missing_param];
}
}
for (var name in url_params) {
if (~url.search(':' + name)) {
url = url.replace(':' + name, encodeURIComponent(url_params[name]));
} else {
if (~url.search(/\?/)) {
url += '&';
} else {
url += '?';
}
url += encodeURIComponent(name) + '=' + encodeURIComponent(url_params[name]);
}
}
return url;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment