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