Bug 19410: Move build_query_params_from_api into a helper
[koha.git] / Koha / REST / Plugin / Objects.pm
1 package Koha::REST::Plugin::Objects;
2
3 # This file is part of Koha.
4 #
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.
9 #
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.
13 #
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.
17
18 use Modern::Perl;
19
20 use Mojo::Base 'Mojolicious::Plugin';
21
22 =head1 NAME
23
24 Koha::REST::Plugin::Objects
25
26 =head1 API
27
28 =head2 Helper methods
29
30 =head3 objects.search
31
32     my $patrons_set = Koha::Patrons->new;
33     my $patrons = $c->objects->search($patrons_set);
34
35 Performs a database search using given Koha::Objects object and query parameters
36
37 Returns a Koha::Objects object
38
39 =cut
40
41 sub register {
42     my ( $self, $app ) = @_;
43
44     $app->helper(
45         'objects.search' => sub {
46             my ( $c, $objects_set ) = @_;
47
48             my $args = $c->validation->output;
49             my $attributes = {};
50
51             # Extract reserved params
52             my ( $filtered_params, $reserved_params ) = $c->extract_reserved_params($args);
53
54             # Merge sorting into query attributes
55             $c->dbic_merge_sorting(
56                 {
57                     attributes => $attributes,
58                     params     => $reserved_params
59                 }
60             );
61
62             # Merge pagination into query attributes
63             $c->dbic_merge_pagination(
64                 {
65                     filter => $attributes,
66                     params => $reserved_params
67                 }
68             );
69
70             $filtered_params = $c->build_query_params( $filtered_params, $reserved_params );
71             # Perform search
72             my $objects = $objects_set->search( $filtered_params, $attributes );
73
74             if ($objects->is_paged) {
75                 $c->add_pagination_headers({
76                     total => $objects->pager->total_entries,
77                     params => $args,
78                 });
79             }
80
81             return $objects;
82         }
83     );
84 }
85
86 1;