Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Merge pull request #702 from metacpan/mickey/mirror_search_endpoint
Added /mirror/search API endpoint
  • Loading branch information
oalders committed Jun 29, 2017
2 parents b1ecd8c + 2787d3c commit 2a39a04
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 2 deletions.
77 changes: 77 additions & 0 deletions lib/MetaCPAN/Document/Mirror.pm
Expand Up @@ -42,5 +42,82 @@ has [qw(inceptdate reitredate)] => (
coerce => 1,
);

__PACKAGE__->meta->make_immutable;

package MetaCPAN::Document::Mirror::Set;

use strict;
use warnings;

use Moose;

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

sub search {
my ( $self, $q ) = @_;
my $query = { match_all => {} };

if ($q) {
my @protocols = grep /^ (?: http | ftp | rsync ) $/x, split /\s+/, $q;

my $query = {
bool => {
must_not => {
bool => {
should => [
map +{ filter => { missing => { field => $_ } } },
@protocols
]
}
}
}
};
}

my @sort = ( sort => [qw( continent country )] );

my $location;

if ( $q and $q =~ /loc\:([^\s]+)/ ) {
$location = [ split( /,/, $1 ) ];
if ($location) {
@sort = (
sort => {
_geo_distance => {
location => [ $location->[1], $location->[0] ],
order => 'asc',
unit => 'km'
}
}
);
}
}

my $ret = $self->es->search(
index => $self->index->name,
type => 'mirror',
body => {
size => 999,
query => $query,
@sort,
},
);
return unless $ret->{hits}{total};

my $data = [
map +{
%{ $_->{_source} },
distance => ( $location ? $_->{sort}[0] : undef )
},
@{ $ret->{hits}{hits} }
];

return {
mirrors => $data,
total => $ret->{hits}{total},
took => $ret->{took}
};
}

__PACKAGE__->meta->make_immutable;
1;
7 changes: 7 additions & 0 deletions lib/MetaCPAN/Server/Controller/Mirror.pm
Expand Up @@ -9,4 +9,11 @@ BEGIN { extends 'MetaCPAN::Server::Controller' }

with 'MetaCPAN::Server::Role::JSONP';

sub search : Path('search') : Args(0) {
my ( $self, $c ) = @_;
my $data = $self->model($c)->raw->search( $c->req->param('q') );
return unless $data;
$c->stash($data);
}

1;
5 changes: 3 additions & 2 deletions t/server/controller/mirror.t
Expand Up @@ -20,7 +20,7 @@ my %tests = (
'content_type=application/json content_type=application',
surrogate_control => undef,
},
'/mirror/_search?q=*' => {
'/mirror/search?q=*' => {
code => 200,
cache_control => 'private',
surrogate_key =>
Expand All @@ -31,7 +31,8 @@ my %tests = (

test_psgi app, sub {
my $cb = shift;
while ( my ( $k, $v ) = each %tests ) {
for my $k ( sort keys %tests ) {
my $v = $tests{$k};
ok( my $res = $cb->( GET $k), "GET $k" );
is( $res->code, $v->{code}, "code " . $v->{code} );
is(
Expand Down

0 comments on commit 2a39a04

Please sign in to comment.