File Coverage

blib/lib/Plack/App/EventSource.pm
Criterion Covered Total %
statement 37 37 100.0
branch 5 6 83.3
condition n/a
subroutine 8 8 100.0
pod 1 1 100.0
total 51 52 98.0


line stmt bran cond sub pod time code
1             package Plack::App::EventSource;
2 2     2   48714 use 5.008001;
  2         4  
  2         50  
3 2     2   6 use strict;
  2         2  
  2         44  
4 2     2   13 use warnings;
  2         2  
  2         43  
5              
6 2     2   430 use parent 'Plack::Component';
  2         249  
  2         9  
7              
8             our $VERSION = "0.02";
9              
10 2     2   7866 use Plack::Util::Accessor qw(handler_cb headers);
  2         160  
  2         8  
11 2     2   1073 use Plack::App::EventSource::Connection;
  2         3  
  2         387  
12              
13             sub call {
14 3     3 1 19180 my $self = shift;
15 3         5 my ($env) = @_;
16              
17 3 100       14 return [405, [], ['Method not allowed']]
18             unless $env->{REQUEST_METHOD} eq 'GET';
19              
20             return sub {
21 2     2   49 my $respond = shift;
22              
23 2 50       5 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         2 @{$self->headers || []}
32             ]
33             ]
34             );
35              
36             my $connection = Plack::App::EventSource::Connection->new(
37             push_cb => sub {
38 2         2 my (@messages) = @_;
39              
40 2         3 foreach my $msg (@messages) {
41 2 100       5 if (ref $msg eq 'HASH') {
42 2         4 my $event = join "\x0d\x0a",
43 4         5 map { "$_: ".$msg->{$_} }
44 1         2 grep { defined $msg->{$_} }
45             qw(event id data retry);
46 1         5 $writer->write("$event\x0d\x0a");
47             }
48             else {
49 1         12 $writer->write("data: $msg\x0d\x0a");
50             }
51             }
52              
53 2         30 $writer->write("\x0d\x0a");
54             },
55             close_cb => sub {
56 2         5 $writer->close;
57             }
58 2         79 );
59              
60 2         4 $self->{handler_cb}->($connection, $env);
61 2         12 };
62             }
63              
64             1;
65             __END__