diff --git a/lib/CF/Helpers/Core.pm b/lib/CF/Helpers/Core.pm index 5712118b7699f91f56f4feda79a0087e37aea517..6aa10097c1f9102013ceac68d309d281dceff206 100644 --- a/lib/CF/Helpers/Core.pm +++ b/lib/CF/Helpers/Core.pm @@ -4,26 +4,31 @@ use base 'Mojolicious::Plugin'; use feature 'signatures'; no warnings qw{ experimental::signatures } ; +use YAML; + sub register ($class, $self, $conf) { - $self->helper(error => sub ($c, $status, $errors=[]) { + $self->helper(error => sub ($c, $status, $msg) { - if ( scalar @_ == 2 ) { - $errors = [{ code => shift, message => shift }]; - } - elsif ( ref $_[0] eq 'ARRAY' ) { - $errors = shift; + if ( ref $msg eq 'ARRAY' ) { + $errors = $msg; } - elsif ( ref $_[0] eq 'HASH' ) { - $errors = [ shift ]; + elsif ( ref $msg eq 'HASH' ) { + $errors = [ $msg ]; } else { - $errors = [{ message => shift, code => undef }]; + $errors = [{ + message => $msg, + path => $c->stash('openapi.path'), + }]; } $c->stash( status => $status, - openapi => { errors => $errors } + openapi => { + status => $status, + errors => $errors, + }, ); return undef; @@ -64,9 +69,81 @@ sub register ($class, $self, $conf) { return $data; }); + $self->helper( search_parametrs => sub( $c, $args ) { + my $conditions = {}; + if ( ref $args->{filter} eq 'ARRAY' ) { + CONDITION: + foreach my $condition ( @{ $args->{filter} } ) { + my ( $column, $op, $arg ) = split /:/, $condition; + my @columns = split /\|/, $column; + my @args = split /\|/, $arg; + + if ( $op eq 'match' ) { + $op = 'ilike'; + @args = map { '%' . $_ . '%' } @args; + } + elsif ( $op =~ /^beg/i ) { + $op = 'ilike'; + @args = map { $_ . '%' } @args; + } + elsif ( $op =~ /^end/i ) { + $op = 'ilike'; + @args = map { '%' . $_ } @args; + } + else { + if ( scalar @args > 1 ) { + $op = 'in'; + } + else { + $op = '='; + } + } + + if ( scalar @columns > 1 ) { + $conditions->{ -or } = [ + map { $_ => { $op => \@args }} @columns + ]; + } + else { + $conditions->{ $column } = { $op => \@args }; + } + } + } + + if ( $args->{fulltext} ) { + $conditions->{fulltext} = { ilike => '%' . $args->{fulltext} . '%'}; + } + + my @order_by = (); + if ( ref $args->{sort} eq 'ARRAY' ) { + COLUMN: + foreach my $column ( @{ $args->{sort} } ) { + $column =~ s/^(\W)*//; + + if ( $1 && $1 eq '-' ) { + push @order_by, { -desc => $column }; + } + else { + push @order_by, $column; + } + } + } + + return ( + $conditions, + { + order_by => \@order_by, +# columns => $args->{columns}, + rows => $args->{limit}, + offset => $args->{offset}, + } + ); + }); + $self->helper( format_timestamp => sub($c, $timestamp, $format) { return $timestamp; }); } 1; +