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.0303';
7              
8 1     1   999 use Moo;
  1         8480  
  1         3  
9 1     1   1551 use strictures 2;
  1         1658  
  1         32  
10 1     1   545 use namespace::clean;
  1         9114  
  1         5  
11              
12 1     1   222 use Carp;
  1         2  
  1         43  
13 1     1   5 use Mojo::UserAgent;
  1         1  
  1         13  
14 1     1   53 use Mojo::JSON qw( decode_json );
  1         1  
  1         36  
15 1     1   5 use Mojo::URL;
  1         1  
  1         9  
16 1     1   35 use Try::Tiny;
  1         2  
  1         319  
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 20084 my ( $self, %args ) = @_;
39              
40 1         6 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         428 my $tx = $self->ua->get($url);
49              
50 1         17932 my $data = _handle_response($tx);
51              
52 1         5 return $data;
53             }
54              
55             sub _handle_response {
56 1     1   3 my ($tx) = @_;
57              
58 1         20 my $data;
59              
60 1         9 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   91 $data = decode_json($body);
66             }
67             catch {
68 0     0   0 croak $body, "\n";
69 1         23 };
70             }
71             else {
72 0         0 croak "Connection error: ", $res->message, "\n";
73             }
74              
75 1         113 return $data;
76             }
77              
78             1;
79              
80             __END__