Bug 14544: [QA Follow-up] DBIx::Class changes
[koha.git] / svc / cataloguing / metasearch
1 #!/usr/bin/perl
2 #
3 # Copyright 2014 ByWater Solutions
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use C4::Service;
23 use Encode qw( encode_utf8 );
24 use Koha::MetaSearcher;
25
26 my ( $query, $response ) = C4::Service->init( catalogue => 1 );
27
28 my ( $query_string, $servers ) = C4::Service->require_params( 'q', 'servers' );
29
30 my $server_errors = {};
31
32 my $sort_key = $query->param( 'sort_key' ) || 'title';
33 my $sort_direction = $query->param( 'sort_direction' ) || 'asc';
34 my $offset = $query->param( 'offset' ) || 0;
35 my $page_size = $query->param( 'page_size' ) || 20;
36 my $fetched = $query->param( 'fetched' ) || 100;
37
38 my $searcher = Koha::MetaSearcher->new( {
39     fetched => $fetched,
40     on_error => sub {
41         my ( $server, $exception ) = @_;
42
43         $server_errors->{ $server->{id} } = $exception->message;
44     },
45 } );
46
47 $searcher->resultset( $query->param('resultset') ) if ( $query->param('resultset') );
48
49 my @server_ids = split( /,/, $servers );
50 my $stats = $searcher->search( \@server_ids, $query_string );
51
52 $searcher->sort( $sort_key, $sort_direction eq 'desc' ? -1 : 1 );
53
54 my @hits;
55
56 foreach my $hit ( $searcher->results( $offset, $page_size ) ) {
57     push @hits, {
58         server => $hit->{server}->{id},
59         index => $hit->{index},
60         record => $hit->{record}->as_xml_record(),
61         metadata => $hit->{metadata}
62     };
63 }
64
65 $response->param(
66     resultset => $searcher->resultset,
67     sort_key => $sort_key,
68     sort_direction => $sort_direction,
69     offset => $offset,
70     page_size => $page_size,
71     errors => $server_errors,
72     hits => \@hits,
73     %$stats
74 );
75
76 C4::Service->return_success( $response );