From 20d68609451eb77382ad6e1f4b7f9b3de0282afb 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 Sponsored-by: Camden County --- 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 1b7176c..01bbde8 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 + + $filter = $c->dbic_merge_sorting({ filter => $filter, params => $params }); + +Generates the DBIC order_by attributes based on I<$params>, and merges into I<$filter>. + +=cut + + $app->helper( + 'dbic_merge_sorting' => sub { + my ( $c, $args ) = @_; + my $filter = $args->{filter}; + + my @order_by = + map { _build_order_atom($_) } + split( /\|/, $args->{params}->{_order_by} ); + + $filter->{order_by} = \@order_by; + return $filter; + } + ); } =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.7.4