From 595ae90fc6642f64b58ecc960080e7f17b548f1a Mon Sep 17 00:00:00 2001 From: Tomas Cohen Arazi Date: Thu, 23 Nov 2017 17:10:42 -0300 Subject: [PATCH] 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 --- Koha/REST/Plugin/Objects.pm | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/Koha/REST/Plugin/Objects.pm b/Koha/REST/Plugin/Objects.pm index eb3f951a39..057f80ee37 100644 --- a/Koha/REST/Plugin/Objects.pm +++ b/Koha/REST/Plugin/Objects.pm @@ -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 ); -- 2.15.0