public
Created

Writing a "url_for" helper for Express

  • Download Gist
examples-and-issues.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// 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
impl.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
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;
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.