Express JS reverse url (Django style)

I use Express JS and I need functionality similar to Django's function reverse. Therefore, if I have a route, for example

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

I would like to use a function like

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

or even better

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

which will give me url /users/15/John. Is there such a function? And if not, do you have any idea how to write such a function (taking into account the Express routing algorithm)?

+5
source share
2 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?', {});
+7
source

I just created a reversable-router package that solves this for other routing issues.

Example from readme:

app.get('/admin/user/:id', 'admin.user.edit', function(req, res, next){
    //...
});

//.. and a helper in the view files:
url('admin.user.edit', {id: 2})
+5
source

All Articles