File Coverage

blib/lib/Plack/App/EventSource.pm
Criterion Covered Total %
statement 34 34 100.0
branch 5 6 83.3
condition n/a
subroutine 8 8 100.0
pod 1 1 100.0
total 48 49 97.9


line stmt bran cond sub pod time code
1             package Plack::App::EventSource;
2 2     2   69228 use 5.008001;
  2         7  
  2         79  
3 2     2   10 use strict;
  2         2  
  2         76  
4 2     2   24 use warnings;
  2         3  
  2         74  
5              
6 2     2   561 use parent 'Plack::Component';
  2         255  
  2         12  
7              
8             our $VERSION = "0.01";
9              
10 2     2   13176 use Plack::Util::Accessor qw(handler_cb headers);
  2         311  
  2         13  
11 2     2   1567 use Plack::App::EventSource::Connection;
  2         5  
  2         524  
12              
13             sub call {
14 3     3 1 39363 my $self = shift;
15 3         6 my ($env) = @_;
16              
17 3 100       20 return [405, [], ['Method not allowed']]
18             unless $env->{REQUEST_METHOD} eq 'GET';
19              
20             return sub {
21 2     2   78 my $respond = shift;
22              
23 2 50       11 my $writer = $respond->(
24             [
25             200,
26             [
27             'Content-Type' => 'text/event-stream; charset=UTF-8',
28             'Cache-Control' =>
29             'no-store, no-cache, must-revalidate, max-age=0',
30             'Access-Control-Allow-Methods' => 'GET',
31 2         5 @{$self->headers || []}
32             ]
33             ]
34             );
35              
36             my $connection = Plack::App::EventSource::Connection->new(
37             push_cb => sub {
38 2         5 my (@messages) = @_;
39              
40 2         5 foreach my $message (@messages) {
41 2 100       7 if (ref $message eq 'HASH') {
42 1         11 $writer->write(
43             join "\x0d\x0a",
44             "id: $message->{id}",
45             "data: $message->{data}", ''
46             );
47             }
48             else {
49 1         13 $writer->write("data: $message\x0d\x0a");
50             }
51             }
52              
53 2         44 $writer->write("\x0d\x0a");
54             },
55             close_cb => sub {
56 2         9 $writer->close;
57             }
58 2         156 );
59              
60 2         22 $self->{handler_cb}->($connection, $env);
61 2         19 };
62             }
63              
64             1;
65             __END__