Browse Source

Bug 19370: Add helper function for order_by attribute generation

This patch introduces a helper function called 'dbic_merge_sorting'
to Koha::REST::Plugin::Query.

This simple function adds SQL::Abstract order_by attribute to the passed
$filter hashref, as explained in the POD.

It introduces a syntax for passing sorting params on the request to the REST api.
The proposed syntax has been found in the wild, and is pretty trivial to parse/work with:

    GET /api/v1/<endpoint>?order_by=+column_1|-column_2|column_3

As explained on the POD, + stands for 'asc' and - for 'desc'. If ommited, it defaults to the
DB engine default (usually asc).

To test:
- Apply this patches
- Run:
  $ sudo koha-shell kohadev
 k$ cd kohaclone
 k$ prove t/Koha/REST/Plugin/Query.t
=> SUCCESS: Tests pass! And they make sense! :-P
- Sign off :-D

Edit: renamed params to match DBIC terminology. My bad :-D (tcohen)

Sponsored-by: Camden County

Signed-off-by: Lari Taskula <lari.taskula@jns.fi>

Signed-off-by: Kyle M Hall <kyle@bywatersolutions.com>

Signed-off-by: Jonathan Druart <jonathan.druart@bugs.koha-community.org>
18.05.x
Tomás Cohen Arazi 5 years ago
committed by Jonathan Druart
parent
commit
5a31321676
  1. 54
      Koha/REST/Plugin/Query.pm

54
Koha/REST/Plugin/Query.pm

@ -65,6 +65,28 @@ Generates the DBIC query from the query parameters.
return ( $filtered_params, $reserved_params );
}
);
=head3 dbic_merge_sorting
$attributes = $c->dbic_merge_sorting({ attributes => $attributes, params => $params });
Generates the DBIC order_by attributes based on I<$params>, and merges into I<$attributes>.
=cut
$app->helper(
'dbic_merge_sorting' => sub {
my ( $c, $args ) = @_;
my $attributes = $args->{attributes};
my @order_by =
map { _build_order_atom($_) }
split( /\|/, $args->{params}->{_order_by} );
$attributes->{order_by} = \@order_by;
return $attributes;
}
);
}
=head2 Internal methods
@ -81,4 +103,36 @@ sub _reserved_words {
return \@reserved_words;
}
=head3 _build_order_atom
my $order_atom = _build_order_atom( $string );
Parses I<$string> and outputs data valid for using in SQL::Abstract order_by attribute
according to the following rules:
string -> I<string>
+string -> I<{ -asc => string }>
-string -> I<{ -desc => string }>
=cut
sub _build_order_atom {
my $string = shift;
if ( $string =~ m/^\+/ ) {
# asc order operator present
$string =~ s/^\+//;
return { -asc => $string };
}
elsif ( $string =~ m/^\-/ ) {
# desc order operator present
$string =~ s/^\-//;
return { -desc => $string };
}
else {
# no order operator present
return $string;
}
}
1;

Loading…
Cancel
Save