Skip to content

Commit

Permalink
Added /favorites/by_user/USER endpoint
Browse files Browse the repository at this point in the history
This endpoint will replace the query in WEB that is used
in several places, and will simplify the code using it.
  • Loading branch information
mickeyn committed May 26, 2017
1 parent 7f8212a commit f8b534e
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
66 changes: 66 additions & 0 deletions lib/MetaCPAN/Document/Favorite.pm
Expand Up @@ -33,5 +33,71 @@ has date => (
default => sub { DateTime->now },
);

__PACKAGE__->meta->make_immutable;

package MetaCPAN::Document::Favorite::Set;

use strict;
use warnings;

use Moose;
extends 'ElasticSearchX::Model::Document::Set';

use MetaCPAN::Util qw( single_valued_arrayref_to_scalar );

sub by_user {
my ( $self, $user, $size ) = @_;
$size ||= 250;

my $favs = $self->es->search(
index => $self->index->name,
type => 'favorite',
body => {
query => { term => { user => $user } },
size => $size,
fields => [qw( date distribution )],
sort => [ { date => 'desc' } ],
}
);
return {} unless $favs->{hits}{total};
my $took = $favs->{took};

my @favs = map { $_->{fields} } @{ $favs->{hits}{hits} };
single_valued_arrayref_to_scalar( \@favs );

# filter out no-latest (backpan only) distributions

my $latest = $self->es->search(
index => $self->index->name,
type => 'release',
body => {
query => {
bool => {
must => [
{ term => { status => 'latest' } },
{
terms => {
distribution =>
[ map { $_->{distribution} } @favs ]
}
},
]
}
},
fields => ['distribution'],
}
);
$took += $latest->{took};

if ( $latest->{hits}{total} ) {
my %has_latest = map { $_->{fields}{distribution}[0] => 1 }
@{ $latest->{hits}{hits} };

@favs = grep { exists $has_latest{ $_->{distribution} } } @favs;
}

return { favorites => \@favs, took => $took };
}

__PACKAGE__->meta->make_immutable;
1;
7 changes: 7 additions & 0 deletions lib/MetaCPAN/Server/Controller/Favorite.pm
Expand Up @@ -28,5 +28,12 @@ sub find : Path('') : Args(2) {
} or $c->detach( '/not_found', [$@] );
}

sub by_user : Path('by_user') : Args(1) {
my ( $self, $c, $user ) = @_;
my $data = $self->model($c)->raw->by_user($user);
$data or return;
$c->stash($data);
}

__PACKAGE__->meta->make_immutable;
1;

0 comments on commit f8b534e

Please sign in to comment.