File Coverage

blib/lib/WWW/FCM/HTTP.pm
Criterion Covered Total %
statement 46 47 97.8
branch 6 8 75.0
condition 4 6 66.6
subroutine 13 13 100.0
pod 2 3 66.6
total 71 77 92.2


line stmt bran cond sub pod time code
1             package WWW::FCM::HTTP;
2 3     3   223548 use 5.008001;
  3         22  
3 3     3   13 use strict;
  3         5  
  3         44  
4 3     3   14 use warnings;
  3         3  
  3         123  
5              
6             our $VERSION = "0.01";
7              
8 3     3   1522 use LWP::UserAgent;
  3         82191  
  3         80  
9 3     3   1087 use LWP::Protocol::https;
  3         199196  
  3         110  
10 3     3   1135 use LWP::ConnCache;
  3         2837  
  3         85  
11 3     3   961 use JSON qw(encode_json);
  3         13975  
  3         16  
12             use Class::Accessor::Lite (
13 3         21 new => 0,
14             rw => [qw/ua api_url api_key json/],
15 3     3   1502 );
  3         2504  
16 3     3   241 use Carp qw(croak);
  3         4  
  3         114  
17              
18 3     3   1011 use WWW::FCM::HTTP::Response;
  3         8  
  3         1798  
19              
20             our $API_URL = 'https://fcm.googleapis.com/fcm/send';
21              
22             sub new {
23 13     13 1 46139 my $class = shift;
24 13 50       61 my %args = ref @_ eq 'HASH' ? %{ @_ } : @_;
  0         0  
25 13 100       168 croak 'Usage: WWW::FCM::HTTP->new(api_key => $api_key)' unless exists $args{api_key};
26              
27 12   66     81 $args{api_url} ||= $API_URL;
28 12   66     145 $args{ua} ||= LWP::UserAgent->new(
29             agent => __PACKAGE__.'/'.$VERSION,
30             conn_cache => LWP::ConnCache->new,
31             );
32              
33 12         7326 bless { %args }, $class;
34             }
35              
36             sub send {
37 10     10 1 37640 my ($self, $payload) = @_;
38 10 100       382 croak 'Usage: $fcm->send(\%payload)' unless ref $payload eq 'HASH';
39              
40 6         50 my $res = $self->ua->request($self->build_request($payload));
41 6         108845 WWW::FCM::HTTP::Response->new($res, $payload->{registration_ids});
42             }
43              
44             sub build_request {
45 6     6 0 80 my ($self, $payload) = @_;
46 6 50       27 croak 'Usage: $gcm->build_request(\%payload)' unless ref $payload eq 'HASH';
47              
48 6         43 my $req = HTTP::Request->new(POST => $self->api_url);
49 6         1387 $req->header(Authorization => 'key='.$self->api_key);
50 6         1157 $req->header('Content-Type' => 'application/json; charset=UTF-8');
51 6         490 $req->content(encode_json $payload);
52              
53 6         344 return $req;
54             }
55              
56             1;
57             __END__