Bug 24528: Add a syntax to x-koha-embed to specify counts
[koha.git] / Koha / REST / Plugin / Query.pm
1 package Koha::REST::Plugin::Query;
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 use List::MoreUtils qw(any);
22 use Scalar::Util qw(reftype);
23
24 use Koha::Exceptions;
25
26 =head1 NAME
27
28 Koha::REST::Plugin::Query
29
30 =head1 API
31
32 =head2 Mojolicious::Plugin methods
33
34 =head3 register
35
36 =cut
37
38 sub register {
39     my ( $self, $app ) = @_;
40
41 =head2 Helper methods
42
43 =head3 extract_reserved_params
44
45     my ( $filtered_params, $reserved_params ) = $c->extract_reserved_params($params);
46
47 Generates the DBIC query from the query parameters.
48
49 =cut
50
51     $app->helper(
52         'extract_reserved_params' => sub {
53             my ( $c, $params ) = @_;
54
55             my $reserved_params;
56             my $filtered_params;
57             my $path_params;
58
59             my $reserved_words = _reserved_words();
60             my @query_param_names = keys %{$c->req->params->to_hash};
61
62             foreach my $param ( keys %{$params} ) {
63                 if ( grep { $param eq $_ } @{$reserved_words} ) {
64                     $reserved_params->{$param} = $params->{$param};
65                 }
66                 elsif ( grep { $param eq $_ } @query_param_names ) {
67                     $filtered_params->{$param} = $params->{$param};
68                 }
69                 else {
70                     $path_params->{$param} = $params->{$param};
71                 }
72             }
73
74             return ( $filtered_params, $reserved_params, $path_params );
75         }
76     );
77
78 =head3 dbic_merge_sorting
79
80     $attributes = $c->dbic_merge_sorting({ attributes => $attributes, params => $params });
81
82 Generates the DBIC order_by attributes based on I<$params>, and merges into I<$attributes>.
83
84 =cut
85
86     $app->helper(
87         'dbic_merge_sorting' => sub {
88             my ( $c, $args ) = @_;
89             my $attributes = $args->{attributes};
90             my $result_set = $args->{result_set};
91
92             if ( defined $args->{params}->{_order_by} ) {
93                 my $order_by = $args->{params}->{_order_by};
94                 if ( reftype($order_by) and reftype($order_by) eq 'ARRAY' ) {
95                     my @order_by = map { _build_order_atom({ string => $_, result_set => $result_set }) }
96                                 @{ $args->{params}->{_order_by} };
97                     $attributes->{order_by} = \@order_by;
98                 }
99                 else {
100                     $attributes->{order_by} = _build_order_atom({ string => $order_by, result_set => $result_set });
101                 }
102             }
103
104             return $attributes;
105         }
106     );
107
108 =head3 _build_query_params_from_api
109
110     my $params = _build_query_params_from_api( $filtered_params, $reserved_params );
111
112 Builds the params for searching on DBIC based on the selected matching algorithm.
113 Valid options are I<contains>, I<starts_with>, I<ends_with> and I<exact>. Default is
114 I<contains>. If other value is passed, a Koha::Exceptions::WrongParameter exception
115 is raised.
116
117 =cut
118
119     $app->helper(
120         'build_query_params' => sub {
121
122             my ( $c, $filtered_params, $reserved_params ) = @_;
123
124             my $params;
125             my $match = $reserved_params->{_match} // 'contains';
126
127             foreach my $param ( keys %{$filtered_params} ) {
128                 if ( $match eq 'contains' ) {
129                     $params->{$param} =
130                       { like => '%' . $filtered_params->{$param} . '%' };
131                 }
132                 elsif ( $match eq 'starts_with' ) {
133                     $params->{$param} = { like => $filtered_params->{$param} . '%' };
134                 }
135                 elsif ( $match eq 'ends_with' ) {
136                     $params->{$param} = { like => '%' . $filtered_params->{$param} };
137                 }
138                 elsif ( $match eq 'exact' ) {
139                     $params->{$param} = $filtered_params->{$param};
140                 }
141                 else {
142                     # We should never reach here, because the OpenAPI plugin should
143                     # prevent invalid params to be passed
144                     Koha::Exceptions::WrongParameter->throw(
145                         "Invalid value for _match param ($match)");
146                 }
147             }
148
149             return $params;
150         }
151     );
152
153 =head3 stash_embed
154
155     $c->stash_embed( $c->match->endpoint->pattern->defaults->{'openapi.op_spec'} );
156
157 =cut
158
159     $app->helper(
160         'stash_embed' => sub {
161
162             my ( $c, $args ) = @_;
163
164             my $spec = $args->{spec} // {};
165
166             my $embed_spec   = $spec->{'x-koha-embed'};
167             my $embed_header = $c->req->headers->header('x-koha-embed');
168
169             Koha::Exceptions::BadParameter->throw("Embedding objects is not allowed on this endpoint.")
170                 if $embed_header and !defined $embed_spec;
171
172             if ( $embed_header ) {
173                 my $THE_embed = {};
174                 foreach my $embed_req ( split /\s*,\s*/, $embed_header ) {
175                     my $matches = grep {lc $_ eq lc $embed_req} @{ $embed_spec };
176
177                     Koha::Exceptions::BadParameter->throw(
178                         error => 'Embeding '.$embed_req. ' is not authorised. Check your x-koha-embed headers or remove it.'
179                     ) unless $matches;
180
181                     _merge_embed( _parse_embed($embed_req), $THE_embed);
182                 }
183
184                 $c->stash( 'koha.embed' => $THE_embed )
185                     if $THE_embed;
186             }
187
188             return $c;
189         }
190     );
191 }
192
193 =head2 Internal methods
194
195 =head3 _reserved_words
196
197     my $reserved_words = _reserved_words();
198
199 =cut
200
201 sub _reserved_words {
202
203     my @reserved_words = qw( _match _order_by _page _per_page );
204     return \@reserved_words;
205 }
206
207 =head3 _build_order_atom
208
209     my $order_atom = _build_order_atom( $string );
210
211 Parses I<$string> and outputs data valid for using in SQL::Abstract order_by attribute
212 according to the following rules:
213
214      string -> I<string>
215     +string -> I<{ -asc => string }>
216     -string -> I<{ -desc => string }>
217
218 =cut
219
220 sub _build_order_atom {
221     my ( $args )   = @_;
222     my $string     = $args->{string};
223     my $result_set = $args->{result_set};
224
225     my $param = $string;
226     $param =~ s/^(\+|\-|\s)//;
227     if ( $result_set ) {
228         my $model_param = $result_set->from_api_mapping->{$param};
229         $param = $model_param if defined $model_param;
230     }
231
232     if ( $string =~ m/^\+/ or
233          $string =~ m/^\s/ ) {
234         # asc order operator present
235         return { -asc => $param };
236     }
237     elsif ( $string =~ m/^\-/ ) {
238         # desc order operator present
239         return { -desc => $param };
240     }
241     else {
242         # no order operator present
243         return $param;
244     }
245 }
246
247 =head3 _parse_embed
248
249     my $embed = _parse_embed( $string );
250
251 Parses I<$string> and outputs data valid for passing to the Kohaa::Object(s)->to_api
252 method.
253
254 =cut
255
256 sub _parse_embed {
257     my $string = shift;
258
259     my $result;
260     my ( $curr, $next ) = split /\s*\.\s*/, $string, 2;
261
262     if ( $next ) {
263         $result->{$curr} = { children => _parse_embed( $next ) };
264     }
265     else {
266         if ( $curr =~ m/^(?<relation>.*)\+count/ ) {
267             my $key = $+{relation} . "_count";
268             $result->{$key} = { is_count => 1 };
269         }
270         else {
271             $result->{$curr} = {};
272         }
273     }
274
275     return $result;
276 }
277
278 =head3 _merge_embed
279
280     _merge_embed( $parsed_embed, $global_embed );
281
282 Merges the hash referenced by I<$parsed_embed> into I<$global_embed>.
283
284 =cut
285
286 sub _merge_embed {
287     my ( $structure, $embed ) = @_;
288
289     my ($root) = keys %{ $structure };
290
291     if ( any { $root eq $_ } keys %{ $embed } ) {
292         # Recurse
293         _merge_embed( $structure->{$root}, $embed->{$root} );
294     }
295     else {
296         # Embed
297         $embed->{$root} = $structure->{$root};
298     }
299 }
300
301 1;