Bug 24191: Make objects.search pass to_model to dbic_merge_sorting
[koha.git] / Koha / REST / Plugin / Objects.pm
blob3d314a784ed34fe1da208017004d4c77accc2d51
1 package Koha::REST::Plugin::Objects;
3 # This file is part of Koha.
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 3 of the License, or (at your option) any later
8 # version.
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License along
15 # with Koha; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 use Modern::Perl;
20 use Mojo::Base 'Mojolicious::Plugin';
22 =head1 NAME
24 Koha::REST::Plugin::Objects
26 =head1 API
28 =head2 Helper methods
30 =head3 objects.search
32 my $patrons_set = Koha::Patrons->new;
33 my $patrons = $c->objects->search( $patrons_set, [\&to_model, \&to_api] );
35 Performs a database search using given Koha::Objects object and query parameters.
36 It (optionally) applies the I<$to_model> function reference before building the
37 query itself, and (optionally) applies I<$to_api> to the result.
39 Returns an arrayref of the hashrefs representing the resulting objects
40 for JSON rendering.
42 Note: Make sure I<$to_model> and I<$to_api> don't autovivify keys.
44 =cut
46 sub register {
47 my ( $self, $app ) = @_;
49 $app->helper(
50 'objects.search' => sub {
51 my ( $c, $objects_set, $to_model, $to_api ) = @_;
53 my $args = $c->validation->output;
54 my $attributes = {};
56 # Extract reserved params
57 my ( $filtered_params, $reserved_params ) = $c->extract_reserved_params($args);
59 # Merge sorting into query attributes
60 $c->dbic_merge_sorting(
62 attributes => $attributes,
63 params => $reserved_params,
64 to_model => $to_model
68 # Merge pagination into query attributes
69 $c->dbic_merge_pagination(
71 filter => $attributes,
72 params => $reserved_params
76 # Call the to_model function by reference, if defined
77 if ( defined $filtered_params ) {
79 # Apply the mapping function to the passed params
80 $filtered_params = $to_model->($filtered_params)
81 if defined $to_model;
82 $filtered_params = $c->build_query_params( $filtered_params, $reserved_params );
85 # Perform search
86 my $objects = $objects_set->search( $filtered_params, $attributes );
88 if ($objects->is_paged) {
89 $c->add_pagination_headers({
90 total => $objects->pager->total_entries,
91 params => $args,
92 });
95 my @objects_list = map {
96 ( defined $to_api )
97 ? $to_api->( $_->TO_JSON )
98 : $_->TO_JSON
99 } $objects->as_list;
101 return \@objects_list;