File Coverage

blib/lib/WebService/YTSearch.pm
Criterion Covered Total %
statement 38 40 95.0
branch 1 2 50.0
condition 2 2 100.0
subroutine 11 12 91.6
pod 1 1 100.0
total 53 57 92.9


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.0401';
7              
8 2     2   1695415 use strictures 2;
  2         4686  
  2         96  
9 2     2   1243 use Carp qw(croak);
  2         7  
  2         193  
10 2     2   995 use Mojo::UserAgent ();
  2         499384  
  2         77  
11 2     2   21 use Mojo::JSON qw(decode_json);
  2         4  
  2         133  
12 2     2   14 use Mojo::URL ();
  2         5  
  2         49  
13 2     2   1676 use Moo;
  2         19191  
  2         13  
14 2     2   6471 use Try::Tiny;
  2         3964  
  2         173  
15 2     2   1302 use namespace::clean;
  2         36175  
  2         14  
16              
17              
18             has key => (
19             is => 'ro',
20             required => 1,
21             );
22              
23              
24             has base => (
25             is => 'rw',
26             default => sub { 'https://www.googleapis.com' },
27             );
28              
29              
30             has ua => (
31             is => 'rw',
32             default => sub { Mojo::UserAgent->new },
33             );
34              
35              
36             sub search {
37 2     2 1 49813 my ( $self, %args ) = @_;
38              
39 2   100     14 my $cmd = delete $args{cmd} || 'search';
40              
41 2         28 my $url = Mojo::URL->new( $self->base )
42             ->path('youtube/v3/' . $cmd)
43             ->query(
44             %args,
45             part => 'snippet',
46             key => $self->key,
47             );
48              
49 2         1249 my $tx = $self->ua->get($url);
50              
51 2         52580 my $data = _handle_response($tx);
52              
53 2         23 return $data;
54             }
55              
56             sub _handle_response {
57 2     2   7 my ($tx) = @_;
58              
59 2         5 my $data;
60              
61 2         18 my $res = $tx->result;
62              
63 2 50       68 if ( $res->is_success ) {
64 2         43 my $body = $res->body;
65             try {
66 2     2   330 $data = decode_json($body);
67             }
68             catch {
69 0     0   0 croak $body, "\n";
70 2         80 };
71             }
72             else {
73 0         0 croak "Connection error: ", $res->message, "\n";
74             }
75              
76 2         73 return $data;
77             }
78              
79             1;
80              
81             __END__