65739fd469d78563f70e120bb8c5cbdfb15ab74f
[catagits/Web-Simple.git] / lib / Web / Dispatch / Wrapper.pm
1 package Web::Dispatch::Wrapper;
2
3 use strictures 1;
4 use Moo;
5 use Exporter 'import';
6
7 our @EXPORT = qw(dispatch_wrapper redispatch_to response_filter);
8
9 extends 'Plack::Middleware';
10
11 has 'wrapper' => (is => 'ro', required => 1);
12
13 sub dispatch_wrapper (&) {
14   my ($code) = @_;
15   __PACKAGE__->from_code($code);
16 }
17
18 sub from_code {
19   my ($class, $code) = @_;
20   $class->new(wrapper => $code);
21 }
22
23 sub redispatch_to {
24   my ($new_path) = @_;
25   __PACKAGE__->from_code(sub {
26     $_[1]->({ %{$_[0]}, PATH_INFO => $new_path });
27   });
28 }
29
30 sub response_filter (&) {
31   my ($code) = @_;
32   __PACKAGE__->from_code(sub {
33     my @result = $_[1]->($_[0]);
34     if (@result) {
35       $code->(@result);
36     } else {
37       ()
38     }
39   });
40 }
41
42 sub to_app {
43   my $code = $_[0]->wrapper;
44   my $app = $_[1];
45   sub { $code->($_[0], $app) }
46 }
47
48 1;