typeoneerror
typeoneerror

Reputation: 56958

Named routes in param pre-conditions

I'd like to use a Route Param Pre-Condition to fetch portfolio items by "slug" if the :slug parameter is set in the URL. I also, however, would like to use a RegExp to match the URI. Are named captures supported in node? Can I give that ([-\w]+) capture a name so the slug pre-condition gets fired?

app.param('slug', function(req, res, next, slug){
  // get thing from database by slug
})

//app.get('/work/view/:slug', function(req, res){
app.get(/^\/work\/view\/([-\w]+)/, function(req, res){
  // render view
})

Upvotes: 1

Views: 2119

Answers (1)

Ekin Koc
Ekin Koc

Reputation: 2997

I'm not sure if this is what you are looking for, but as far as I know, there is no direct way do do what you need. However, you can use a named param ("slug") and add a Regex precodition along with your own to achieve the same effect.

Take a look at visionmedia's express-params module here. I expect it to be maintained just fine since it's from the creator of express itself.

What you are gonna do (after installing express-params) is basically something like this:

app.param('slug', /^[-\w]+$/);

app.param('slug', function(req, res, next, slug){
  // get thing from database by slug
});

app.get('/work/view/:slug', function(req, res){
  //render view
});

I did not test any of this though.

Upvotes: 3

Related Questions