Skip to content

Commit 48638d3

Browse files
committed
Move more autocomplete logic from web to api, fixes #257
1 parent 56aaecd commit 48638d3

File tree

2 files changed

+36
-8
lines changed

2 files changed

+36
-8
lines changed

lib/MetaCPAN/Document/File.pm

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -901,4 +901,37 @@ sub history {
901901
return $search->sort([{ "file.date" => "desc"}]);
902902
}
903903

904+
sub _not_rogue {
905+
my @rogue_dists = map { { term => { 'file.distribution' => $_ } } } @ROGUE_DISTRIBUTIONS;
906+
return { not => { filter => { or => \@rogue_dists } } };
907+
}
908+
909+
sub autocomplete {
910+
my ($self, @terms) = @_;
911+
my $query = join(" ", @terms);
912+
return $self unless $query;
913+
$query =~ s/::/ /g;
914+
my @query = split( /\s+/, $query );
915+
my $should = [
916+
map {
917+
{ field => { 'documentation.analyzed' => "$_*" } },
918+
{ field => { 'documentation.camelcase' => "$_*" } }
919+
} grep {$_} @query
920+
];
921+
return $self->query({
922+
custom_score => {
923+
query => { bool => { should => $should } },
924+
script => "_score - doc['documentation'].stringValue.length()/100",
925+
}
926+
})->filter({
927+
and => [
928+
$self->_not_rogue,
929+
{ exists => { field => 'documentation' } },
930+
{ term => { 'file.indexed' => \1 } },
931+
{ term => { 'file.authorized' => \1 } },
932+
{ term => { 'file.status' => 'latest' } },
933+
]
934+
});
935+
}
936+
904937
__PACKAGE__->meta->make_immutable;

lib/MetaCPAN/Server/Controller/Search/Autocomplete.pm

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,10 @@ with 'MetaCPAN::Server::Role::JSONP';
55

66
has '+type' => ( default => 'file' );
77

8-
sub get : Chained('/search/index') : PathPart('autocomplete') : Args(0) :
9-
ActionClass('Deserialize') {
8+
sub get : Local : Path('') : Args(0) {
109
my ( $self, $c ) = @_;
11-
my $frac = join( ' ', $c->req->param('q') );
12-
my $size = $c->req->params->{size};
13-
$size = 20 unless(defined $size);
14-
$c->detach('/not_allowed') unless($size =~ /^\d+$/ && $size >= 0 && $size <= 100);
15-
my $data = $c->model('CPAN::File')->prefix($frac)->inflate(0)
16-
->fields( [qw(documentation release author distribution)] )->size($size);
10+
my $data = $c->model('CPAN::File')->autocomplete($c->req->param("q"))->raw
11+
->fields( [qw(documentation release author distribution)] );
1712
$c->stash($data->all);
1813
}
1914

0 commit comments

Comments
 (0)