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.0602';
7              
8 1     1   1032 use strictures 2;
  1         1377  
  1         37  
9 1     1   182 use Carp qw(croak);
  1         2  
  1         42  
10 1     1   5 use Mojo::UserAgent ();
  1         2  
  1         15  
11 1     1   4 use Mojo::JSON qw(decode_json);
  1         2  
  1         37  
12 1     1   5 use Mojo::URL ();
  1         2  
  1         12  
13 1     1   447 use Moo;
  1         9017  
  1         5  
14 1     1   1780 use Try::Tiny;
  1         1152  
  1         49  
15 1     1   425 use namespace::clean;
  1         8046  
  1         5  
16              
17              
18             has base => (
19             is => 'rw',
20             default => sub { 'https://acousticbrainz.org' },
21             );
22              
23              
24             has ua => (
25             is => 'rw',
26             default => sub { Mojo::UserAgent->new() },
27             );
28              
29              
30             sub fetch {
31 3     3 1 26019 my ( $self, %args ) = @_;
32              
33 3 100       23 croak 'No mbid provided' unless $args{mbid};
34 2 100       13 croak 'No endpoint provided' unless $args{endpoint};
35              
36             my $url = Mojo::URL->new($self->base)
37 1         9 ->path('/api/v1/' . $args{mbid} . '/'. $args{endpoint});
38 1 50       295 $url->query(%{ $args{query} }) if $args{query};
  1         6  
39              
40 1         99 my $tx = $self->ua->get($url);
41              
42 1         17702 my $data = _handle_response($tx);
43              
44 1         8 return $data;
45             }
46              
47             sub _handle_response {
48 1     1   3 my ($tx) = @_;
49              
50 1         2 my $data;
51              
52 1         7 my $res = $tx->result;
53              
54 1 50       27 if ( $res->is_success ) {
55 1         16 my $body = $res->body;
56             try {
57 1     1   106 $data = decode_json($body);
58             }
59             catch {
60 0     0   0 croak $body, "\n";
61 1         26 };
62             }
63             else {
64 0         0 croak "Connection error: ", $res->message;
65             }
66              
67 1         139 return $data;
68             }
69              
70             1;
71              
72             __END__