File Coverage

blib/lib/WebService/AcousticBrainz.pm
Criterion Covered Total %
statement 41 43 95.3
branch 6 8 75.0
condition n/a
subroutine 11 12 91.6
pod 1 1 100.0
total 59 64 92.1


line stmt bran cond sub pod time code
1             package WebService::AcousticBrainz;
2             our $AUTHORITY = 'cpan:GENE';
3              
4             # ABSTRACT: Access to the AcousticBrainz API
5              
6             our $VERSION = '0.0601';
7              
8 1     1   2613 use Moo;
  1         11103  
  1         5  
9 1     1   2027 use strictures 2;
  1         1715  
  1         40  
10 1     1   1276 use namespace::clean;
  1         13248  
  1         7  
11              
12 1     1   290 use Carp;
  1         3  
  1         141  
13 1     1   10 use Mojo::UserAgent;
  1         2  
  1         20  
14 1     1   59 use Mojo::JSON qw( decode_json );
  1         2  
  1         49  
15 1     1   6 use Mojo::URL;
  1         2  
  1         13  
16 1     1   43 use Try::Tiny;
  1         16  
  1         460  
17              
18              
19             has base => (
20             is => 'rw',
21             default => sub { 'https://acousticbrainz.org' },
22             );
23              
24              
25             has ua => (
26             is => 'rw',
27             default => sub { Mojo::UserAgent->new() },
28             );
29              
30              
31             sub fetch {
32 3     3 1 30026 my ( $self, %args ) = @_;
33              
34 3 100       27 croak 'No mbid provided' unless $args{mbid};
35 2 100       17 croak 'No endpoint provided' unless $args{endpoint};
36              
37             my $url = Mojo::URL->new($self->base)
38 1         13 ->path('/api/v1/' . $args{mbid} . '/'. $args{endpoint});
39 1 50       372 $url->query(%{ $args{query} }) if $args{query};
  1         11  
40              
41 1         133 my $tx = $self->ua->get($url);
42              
43 1         23195 my $data = _handle_response($tx);
44              
45 1         7 return $data;
46             }
47              
48             sub _handle_response {
49 1     1   3 my ($tx) = @_;
50              
51 1         4 my $data;
52              
53 1         8 my $res = $tx->result;
54              
55 1 50       33 if ( $res->is_success ) {
56 1         20 my $body = $res->body;
57             try {
58 1     1   137 $data = decode_json($body);
59             }
60             catch {
61 0     0   0 croak $body, "\n";
62 1         33 };
63             }
64             else {
65 0         0 croak "Connection error: ", $res->message;
66             }
67              
68 1         176 return $data;
69             }
70              
71             1;
72              
73             __END__