Navigation Menu

Skip to content

Commit

Permalink
created /author/by_user endpoint to replace web direct query
Browse files Browse the repository at this point in the history
  • Loading branch information
mickeyn committed Sep 27, 2016
1 parent 05ec1e0 commit ed082c6
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
27 changes: 27 additions & 0 deletions lib/MetaCPAN/Server/Controller/Author.pm
Expand Up @@ -3,6 +3,8 @@ package MetaCPAN::Server::Controller::Author;
use strict;
use warnings;

use MetaCPAN::Util qw( single_valued_arrayref_to_scalar );

use Moose;

BEGIN { extends 'MetaCPAN::Server::Controller' }
Expand Down Expand Up @@ -54,4 +56,29 @@ sub get : Path('') : Args(1) {
['The requested field(s) could not be found'] );
}

# endpoint: /author/by_user?[fields=<csv_fields>&]users=<csv_user_ids>
sub by_user : Path('by_user') : Args(0) {
my ( $self, $c ) = @_;
my @users = split /,/ => $c->req->parameters->{users};
my @fields = split /,/ => $c->req->parameters->{fields};

my $res = $self->model($c)->raw->filter(
{
bool =>
{ should => [ map { { term => { user => $_ } } } @users ] }
}
);
$res = $res->fields( \@fields ) if @fields;
$res = $res->size(5000)->all->{hits}{hits};

$c->stash(
{
authors => [
map { single_valued_arrayref_to_scalar( $_->{fields} ) }
@{$res}
]
}
);
}

1;
24 changes: 24 additions & 0 deletions lib/MetaCPAN/Util.pm
Expand Up @@ -8,12 +8,14 @@ use version;

use Digest::SHA1;
use Encode;
use Ref::Util qw( is_arrayref );
use Sub::Exporter -setup => {
exports => [
'author_dir', 'digest',
'extract_section', 'fix_pod',
'fix_version', 'numify_version',
'pod_lines', 'strip_pod',
'single_valued_arrayref_to_scalar'
]
};

Expand Down Expand Up @@ -125,6 +127,28 @@ sub pod_lines {
return \@return, $slop;
}

sub single_valued_arrayref_to_scalar {
my ( $array, $fields ) = @_;
my $is_arrayref = is_arrayref($array);

$array = [$array] unless $is_arrayref;

my $has_fields = defined $fields ? 1 : 0;
$fields ||= [];
my %fields_to_extract = map { $_ => 1 } @{$fields};
foreach my $hash ( @{$array} ) {
foreach my $field ( %{$hash} ) {
next if ( $has_fields and not $fields_to_extract{$field} );
my $value = $hash->{$field};

# We only operate when have an ArrayRef of one value
next unless is_arrayref($value) && scalar @{$value} == 1;
$hash->{$field} = $value->[0];
}
}
return $is_arrayref ? $array : @{$array};
}

1;

__END__
Expand Down

0 comments on commit ed082c6

Please sign in to comment.