SystemicPlural
SystemicPlural

Reputation: 5789

How to write a route that targets an action from a path paramater

If I have multiple urls like '/some/url/path/foo/bar1', '/some/url/path/foo/bar2', '/some/url/path/foo/bar3' etc. How can I write a single route that will direct the urls to the foo controller and the action of bar1, bar2, bar3 etc.

EG. (only this doesn't work.)

'/some/url/path/foo/:bar' : 'foo.:bar'

Upvotes: 1

Views: 36

Answers (1)

Meeker
Meeker

Reputation: 5979

There are different ways to do this. I might suggest that you don't need the different actions in your controller, but just have different cases in a single action that respond to a url param (ex bar). That would be more inline with conventions.

However, you can accomplish what you want with the following.

Create your route

'/some/url/path/foo/:action': {
     controller: 'FooController',
     action: 'getAction'
}

Then in that controller create a getAction method. This method can now use req.param.action variable to find an execute the corresponding action.

FooController.getAction = function(req,res,next){

    return sails.controllers.foo[req.param.action](req,res,next)

}

Upvotes: 1

Related Questions