Link Here
|
0 |
- |
1 |
package Koha::REST::Plugin::Pagination; |
|
|
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 |
sub register { |
23 |
my ( $self, $app ) = @_; |
24 |
|
25 |
$app->helper( |
26 |
'links_header' => sub { |
27 |
my ( $c, $params ) = @_; |
28 |
|
29 |
my $total = $params->{total}; |
30 |
my $page = $params->{page}; |
31 |
my $per_page = $params->{per_page}; |
32 |
|
33 |
my $pages = int $total / $per_page; |
34 |
$pages++ |
35 |
if $total % $per_page > 0; |
36 |
|
37 |
|
38 |
my @links; |
39 |
|
40 |
if ( $pages > 1 and $page > 1 ) { # Previous exists? |
41 |
push @links, |
42 |
_build_link( $c, { page => $page - 1, per_page => $per_page, rel => 'prev' } ); |
43 |
} |
44 |
|
45 |
if ( $pages > 1 and $page < $pages ) { # Next exists? |
46 |
push @links, |
47 |
_build_link( $c, { page => $page + 1, per_page => $per_page, rel => 'next' } ); |
48 |
} |
49 |
|
50 |
push @links, _build_link( $c, { page => 1, per_page => $per_page, rel => 'first' } ); |
51 |
push @links, _build_link( $c, { page => $pages, per_page => $per_page, rel => 'last' } ); |
52 |
|
53 |
$c->res->headers->add( 'Link' => join( ',', @links ) ); |
54 |
|
55 |
return $c; |
56 |
} |
57 |
); |
58 |
|
59 |
$app->helper( |
60 |
'total_count_header' => sub { |
61 |
my ( $c, $params ) = @_; |
62 |
my $total_count = $params->{total_count}; |
63 |
|
64 |
$c->res->headers->add( 'X-Total-Count' => $total_count ) |
65 |
if $total_count; |
66 |
|
67 |
return $c; |
68 |
} |
69 |
); |
70 |
} |
71 |
|
72 |
sub _build_link { |
73 |
my ( $c, $params ) = @_; |
74 |
|
75 |
my $link = '<' |
76 |
. $c->req->url->clone->query( |
77 |
[ 'per_page' => $params->{per_page}, |
78 |
'page' => $params->{page} |
79 |
] |
80 |
)->to_abs |
81 |
. '>; rel="' |
82 |
. $params->{rel} . '"'; |
83 |
|
84 |
# TODO: Find a better solution for this horrible (but needed) fix |
85 |
$link =~ s|api\/v1\/app\.pl\/||; |
86 |
|
87 |
return $link; |
88 |
} |
89 |
|
90 |
1; |