Bug 30165: (follow-up) Allow objects.search usage outside OpenAPI
[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
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use Mojo::Base 'Mojolicious::Plugin';
21
22 use JSON;
23
24 =head1 NAME
25
26 Koha::REST::Plugin::Objects
27
28 =head1 API
29
30 =head2 Helper methods
31
32 =cut
33
34 sub register {
35     my ( $self, $app ) = @_;
36
37 =head3 objects.find
38
39     my $patrons_rs = Koha::Patrons->new;
40     my $patrons = $c->objects->find( $patrons_rs, $id );
41
42 Performs a database search using given Koha::Objects object and the $id.
43
44 Returns I<undef> if no object is found Returns the I<API representation> of
45 the requested object. It passes through any embeds if specified.
46
47 =cut
48
49     $app->helper(
50         'objects.find' => sub {
51             my ( $c, $result_set, $id ) = @_;
52
53             my $attributes = {};
54
55             # Look for embeds
56             my $embed = $c->stash('koha.embed');
57             # Generate prefetches for embedded stuff
58             $c->dbic_merge_prefetch(
59                 {
60                     attributes => $attributes,
61                     result_set => $result_set
62                 }
63             );
64
65             my $object = $result_set->find( $id, $attributes );
66
67             return unless $object;
68
69             return $object->to_api({ embed => $embed });
70         }
71     );
72
73 =head3 objects.search
74
75     my $patrons_rs = Koha::Patrons->new;
76     my $patrons = $c->objects->search( $patrons_rs );
77
78 Performs a database search using given Koha::Objects object and query parameters.
79
80 Returns an arrayref of the hashrefs representing the resulting objects
81 for API rendering.
82
83 Warning: this helper adds pagination headers to the calling controller, and thus
84 shouldn't be called twice in it.
85
86 =cut
87
88     $app->helper(
89         'objects.search' => sub {
90             my ( $c, $result_set ) = @_;
91
92             my $args = $c->validation->output;
93             my $attributes = {};
94
95             # Extract reserved params
96             my ( $filtered_params, $reserved_params, $path_params ) = $c->extract_reserved_params($args);
97             # Privileged reques?
98             my $is_public = $c->stash('is_public');
99             # Look for embeds
100             my $embed = $c->stash('koha.embed');
101
102             # Merge sorting into query attributes
103             $c->dbic_merge_sorting(
104                 {
105                     attributes => $attributes,
106                     params     => $reserved_params,
107                     result_set => $result_set
108                 }
109             );
110
111             # If no pagination parameters are passed, default
112             $reserved_params->{_per_page} //= C4::Context->preference('RESTdefaultPageSize');
113             $reserved_params->{_page}     //= 1;
114
115             unless ( $reserved_params->{_per_page} == -1 ) {
116                 # Merge pagination into query attributes
117                 $c->dbic_merge_pagination(
118                     {
119                         filter => $attributes,
120                         params => $reserved_params
121                     }
122                 );
123             }
124
125             # Generate prefetches for embedded stuff
126             $c->dbic_merge_prefetch(
127                 {
128                     attributes => $attributes,
129                     result_set => $result_set
130                 }
131             );
132
133             # Call the to_model function by reference, if defined
134             if ( defined $filtered_params ) {
135
136                 # Apply the mapping function to the passed params
137                 $filtered_params = $result_set->attributes_from_api($filtered_params);
138                 $filtered_params = $c->build_query_params( $filtered_params, $reserved_params );
139             }
140
141             if (   defined $reserved_params->{q}
142                 || defined $reserved_params->{query}
143                 || defined $reserved_params->{'x-koha-query'} )
144             {
145                 $filtered_params //= {};
146
147                 my @query_params_array;
148
149                 # query in request body, JSON::Validator already decoded it
150                 push @query_params_array, $reserved_params->{query}
151                   if defined $reserved_params->{query};
152
153                 my $json = JSON->new;
154
155                 if ( ref($reserved_params->{q}) eq 'ARRAY' ) {
156                     # q is defined as multi => JSON::Validator generates an array
157                     foreach my $q ( @{ $reserved_params->{q} } ) {
158                         push @query_params_array, $json->decode($q)
159                         if $q; # skip if exists but is empty
160                     }
161                 }
162                 else {
163                     # objects.search called outside OpenAPI context
164                     # might be a hashref
165                     push @query_params_array, $json->decode($reserved_params->{q})
166                         if $reserved_params->{q};
167                 }
168
169                 push @query_params_array,
170                   $json->decode( $reserved_params->{'x-koha-query'} )
171                   if defined $reserved_params->{'x-koha-query'};
172
173                 my $query_params;
174
175                 if ( scalar(@query_params_array) > 1 ) {
176                     $query_params = { '-and' => \@query_params_array };
177                 }
178                 else {
179                     $query_params = $query_params_array[0];
180                 }
181
182                 $filtered_params = $c->merge_q_params( $filtered_params, $query_params, $result_set );
183             }
184
185             # If search_limited exists, use it
186             $result_set = $result_set->search_limited,
187                 if $result_set->can('search_limited');
188
189             # Perform search
190             my $objects = $result_set->search( $filtered_params, $attributes );
191             my $total   = $result_set->search->count;
192
193             $c->add_pagination_headers(
194                 {
195                     total      => ($objects->is_paged ? $objects->pager->total_entries : $objects->count),
196                     base_total => $total,
197                     params     => $args,
198                 }
199             );
200
201             return $objects->to_api({ embed => $embed, public => $is_public });
202         }
203     );
204 }
205
206 1;