File Coverage

blib/lib/WebService/YTSearch.pm
Criterion Covered Total %
statement 37 39 94.8
branch 1 2 50.0
condition n/a
subroutine 11 12 91.6
pod 1 1 100.0
total 50 54 92.5


line stmt bran cond sub pod time code
1             package WebService::YTSearch;
2             our $AUTHORITY = 'cpan:GENE';
3              
4             # ABSTRACT: Search YouTube
5              
6             our $VERSION = '0.0302';
7              
8 1     1   2048 use Moo;
  1         9393  
  1         5  
9 1     1   1745 use strictures 2;
  1         1399  
  1         32  
10 1     1   860 use namespace::clean;
  1         10616  
  1         6  
11              
12 1     1   243 use Carp;
  1         2  
  1         50  
13 1     1   4 use Mojo::UserAgent;
  1         2  
  1         14  
14 1     1   44 use Mojo::JSON qw( decode_json );
  1         2  
  1         36  
15 1     1   4 use Mojo::URL;
  1         2  
  1         10  
16 1     1   35 use Try::Tiny;
  1         2  
  1         357  
17              
18              
19             has key => (
20             is => 'ro',
21             required => 1,
22             );
23              
24              
25             has base => (
26             is => 'rw',
27             default => sub { 'https://www.googleapis.com' },
28             );
29              
30              
31             has ua => (
32             is => 'rw',
33             default => sub { Mojo::UserAgent->new },
34             );
35              
36              
37             sub search {
38 1     1 1 21756 my ( $self, %args ) = @_;
39              
40 1         10 my $url = Mojo::URL->new( $self->base )
41             ->path('youtube/v3/search')
42             ->query(
43             %args,
44             part => 'snippet',
45             key => $self->key,
46             );
47              
48 1         467 my $tx = $self->ua->get($url);
49              
50 1         19762 my $data = _handle_response($tx);
51              
52 1         19 return $data;
53             }
54              
55             sub _handle_response {
56 1     1   3 my ($tx) = @_;
57              
58 1         14 my $data;
59              
60 1         8 my $res = $tx->result;
61              
62 1 50       25 if ( $res->is_success ) {
63 1         16 my $body = $res->body;
64             try {
65 1     1   107 $data = decode_json($body);
66             }
67             catch {
68 0     0   0 croak $body, "\n";
69 1         28 };
70             }
71             else {
72 0         0 croak "Connection error: ", $res->message, "\n";
73             }
74              
75 1         125 return $data;
76             }
77              
78             1;
79              
80             __END__