File Coverage

blib/lib/UserAgent/Any/JSON.pm
Criterion Covered Total %
statement 37 37 100.0
branch 6 6 100.0
condition n/a
subroutine 9 9 100.0
pod n/a
total 52 52 100.0


line stmt bran cond sub pod time code
1             package UserAgent::Any::JSON;
2              
3 4     4   916481 use 5.036;
  4         19  
4              
5 4     4   25 use Carp;
  4         12  
  4         350  
6 4     4   2711 use Moo;
  4         40953  
  4         27  
7 4     4   10539 use UserAgent::Any::JSON::Response;
  4         18  
  4         224  
8 4     4   2814 use UserAgent::Any::Wrapper 'wrap_get_like_methods', 'wrap_post_like_methods';
  4         41986  
  4         354  
9              
10 4     4   40 use namespace::clean;
  4         7  
  4         65  
11              
12             our $VERSION = 0.05;
13              
14             extends 'UserAgent::Any';
15              
16             has _converter => (
17             init_arg => 'json',
18             is => 'ro',
19             default => sub { require JSON; JSON->new },
20             );
21              
22             # This is not specific to GET and can actually handle any verb that does not
23             # take a request body.
24 4     4   16886 sub _generate_get_request ($self, $url, @headers) {
  4         8  
  4         10  
  4         7  
  4         6  
25 4 100       204 croak 'Invalid number of arguments, expected an even sized list after the url' if @headers % 2;
26 3         15 return _generate_post_request($self, $url, @headers);
27             }
28              
29             # The only difference with the 'get' version is that this handles the request
30             # body.
31 10     10   198188 sub _generate_post_request ($self, $url, @args) {
  10         24  
  10         20  
  10         20  
  10         24  
32 10         18 my $body;
33 10 100       41 $body = pop @args if @args % 2;
34             return (
35 10 100       458 $url,
36             'Accept' => 'application/json',
37             'Content-Type' => 'application/json',
38             @args,
39             defined $body ? ($self->_converter->encode($body)) : ());
40             }
41              
42 10     10   24798 sub _process_response ($self, $res, @) {
  10         19  
  10         16  
  10         12  
43 10         237 return UserAgent::Any::JSON::Response->new(res => $res, converter => $self->_converter);
44             }
45              
46             wrap_get_like_methods('UserAgent::Any', \&_generate_get_request, \&_process_response);
47             wrap_post_like_methods('UserAgent::Any', \&_generate_post_request, \&_process_response);
48              
49             1;
50              
51             __END__