Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express JS reverse URL route (Django style)

I'm using Express JS and I want a functionality similar to Django's reverse function. So if I have a route, for example

app.get('/users/:id/:name', function(req, res) { /* some code */ } )

I'd like to use a function for example

reverse('/users/:id/:name', 15, 'John');

or even better

reverse('/users/:id/:name', { id : 15, name : 'John' });

which will give me the url /users/15/John. Does such function exist? And if not then do you have any ideas how to write such function (considering Express' routing algorithm)?

like image 844
freakish Avatar asked Apr 05 '12 11:04

freakish


1 Answers

Here is your code:

function reverse(url, obj) { 
    return url.replace(/(\/:\w+\??)/g, function (m, c) { 
        c=c.replace(/[/:?]/g, ''); 
        return obj[c] ? '/' + obj[c] : ""; 
    }); 
}

reverse('/users/:id/:name', { id: 15, name: 'John' });
reverse('/users/:id?', { id: 15});
reverse('/users/:id?', {});
like image 168
cababunga Avatar answered Oct 04 '22 15:10

cababunga