Bug 19686: Add objects.search a 'to_model' param

This patch introduces a new parameter to the objects.search Mojo helper.
The idea behind this, is that if there's any attribute name mapping
between the DB objects and the API exposed ones, we should be able to
pass it to objects.search so the filtering query params are mapped
correctly for building the DBIC query, like this example:

  my $patrons_set = Koha::Patrons->new;
  my @patrons = $c->objects->search( $patrons_set,
                                     \&to_model
                                    )->as_list;
  # and probably
  @patrons = map {to_api($_)} @patrons;

The to_model function needs to avoid autovivification, to prevent
messing with the query parameters (undef params).

To test:
- Apply this patches
- Run:
  $ kshell
 k$ prove t/db_dependent/Koha/REST/Plugin/Objects.t
=> SUCCESS: Tests pass! Params get mapped!
- Sign off :-D

Signed-off-by: Tomas Cohen Arazi <tomascohen@theke.io>

Signed-off-by: David Bourgault <david.bourgault@inlibro.com>

Signed-off-by: Kyle M Hall <kyle@bywatersolutions.com>

Signed-off-by: Jonathan Druart <jonathan.druart@bugs.koha-community.org>
This commit is contained in:
Tomas Cohen Arazi 2017-11-23 17:10:42 -03:00 committed by Jonathan Druart
parent 37ed1111ce
commit 4bd62d0a8c
1 changed files with 16 additions and 4 deletions

View File

@ -30,9 +30,13 @@ Koha::REST::Plugin::Objects
=head3 objects.search
my $patrons_set = Koha::Patrons->new;
my $patrons = $c->objects->search($patrons_set);
my $patrons = $c->objects->search( $patrons_set, [\&to_model] );
Performs a database search using given Koha::Objects object and query parameters
Performs a database search using given Koha::Objects object and query parameters.
Optionally, it applies the I<$to_model> function reference before building the
query itself.
Note: Make sure I<$to_model> doesn't autovivify keys.
Returns a Koha::Objects object
@ -43,7 +47,7 @@ sub register {
$app->helper(
'objects.search' => sub {
my ( $c, $objects_set ) = @_;
my ( $c, $objects_set, $to_model ) = @_;
my $args = $c->validation->output;
my $attributes = {};
@ -67,7 +71,15 @@ sub register {
}
);
$filtered_params = $c->build_query_params( $filtered_params, $reserved_params );
# Call the to_model function by reference, if defined
if ( defined $filtered_params ) {
# Apply the mapping function to the passed params
$filtered_params = $to_model->($filtered_params)
if defined $to_model;
$filtered_params = $c->build_query_params( $filtered_params, $reserved_params );
}
# Perform search
my $objects = $objects_set->search( $filtered_params, $attributes );