How to pass arguments for Mojolicious filter

Sometimes we are required to check incoming IDs not only for format, but also for existence in DB.

But different IDs we should check through different models.

This pull request tries to add this functionality. If it will be appiled you can do next:

$v->required( 'invoice_id', [ data_exists => 'Invoice' ] );
$v->required( 'order_id', [data_exists => 'Order' ] );

And the fileter:

$v->add_filter( data_exists => sub { data_exists( $app, @_ ) } );

sub data_exists {
    my( $app, $v, $name, $value, $model ) =  @_;

    my $obj =  $app->rows( $model )->find( $value )
       or return ();

    return $obj;

If you want your model do advanced decision about its data accessible or not you may pass current context:

$v->required( 'invoice_id', [ data_exists => $c, 'Invoice' ] );

The filter:

sub data_exists {
    my( $v, $name, $value, $c, $model ) =  @_;

    my $obj =  $c->rows( $model )->find( $value )
       or return ();

    return $obj;

And somewhere in the model:

sub rows {
    my( $c, $table_name ) = @_;
    $c->db->relation_ship( $table_name )->search({ user_id => $c->uid });

So after validation you are guarantied to have objects which are allowed to access only for current user.

And there is no way to access other objects the user do not own

Leave a comment

About KES

user-pic I blog about Perl.