param info for mojolicious routing using under

Viewed 46

I'm using the under method in Mojolicious routing to handle some route permissions. I was hoping to handle nearly all routes by passing to a common controller function, however it doesn't appear that under captures all of the params that I need. Here's a MWE:

package Test;
use Mojo::Base 'Mojolicious', -signatures;

sub startup ($app) {
  my $config = $app->plugin('NotYAMLConfig');
  $app->secrets($config->{secrets});

  $app->routes->under('/api')->to('Permission#allow')->get('/users/:user_id')->to('User#getUser');
  $app->routes->under('/api/other/users/:user_id')->to('Permission#allow')->get('/')->to('User#getUser');
}
1;

with the module Permission as:

package Test::Controller::Permission;
use Mojo::Base 'Mojolicious::Controller', -signatures;

sub allow ($c) {
  print $c->dumper($c->stash->{'mojo.captures'});
  return 1;
}
1;

and module User.pm is:

package Test::Controller::User;
use Mojo::Base 'Mojolicious::Controller', -signatures;

sub getUser ($c) {
  $c->render(text => 'The user_id is: ' . $c->param('user_id'));
}
1;

There is a basic script called test that was created with the mojo generate and running script/test /api/users/3 shows that the user_id is not available as a $c->param('user_id') in the Permission#allow sub, however is in the User#getUser sub.

Running script/test /api/other/users/3 does show that now Permission#allow has user_id available as a param.

This is clearly the difference in defining the under part of the route. My question is do I need to defined all of the under in my routes (I have about 20 in my full app), or is there another way to capture the params in a more general way.

I have noticed that the allow sub has the url of the full route (with the route params).

0 Answers
Related