From 5a31321676e8bfd02d3a7c1888b89a7fc01166f4 Mon Sep 17 00:00:00 2001 From: Tomas Cohen Arazi Date: Tue, 26 Sep 2017 15:17:43 -0300 Subject: [PATCH] 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/?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 Signed-off-by: Kyle M Hall Signed-off-by: Jonathan Druart --- Koha/REST/Plugin/Query.pm | 54 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/Koha/REST/Plugin/Query.pm b/Koha/REST/Plugin/Query.pm index 1b7176c983..32656a401b 100644 --- a/Koha/REST/Plugin/Query.pm +++ b/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 -> 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; -- 2.39.5