blib/lib/Plack/Middleware/APISchema/ResponseValidator.pm untested

filter: Statementstmt 0.0% 0 / 56 Branchbran 0.0% 0 / 2 Conditioncond 0.0% 0 / 10 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 82 CC 2 SCAR 9.6
CC
2
Cov
0%
call
6.0
router
2.0
BEGIN
2.0
CRAP 2.6
1 package Plack::Middleware::APISchema::ResponseValidator;
2 use strict;
3 use warnings;
4  
5 use parent qw(Plack::Middleware);
6 use Plack::Util ();
7 use Plack::Util::Accessor qw(schema validator);
8 use Plack::Response;
9 use APISchema::Generator::Router::Simple;
10 use APISchema::Validator;
11 use JSON::XS qw(encode_json);
12  
13 use constant DEFAULT_VALIDATOR_CLASS => 'Valiemon';
14  
15 sub call {
16 my ($self, $env) = @_;
17  
18 Plack::Util::response_cb($self->app->($env), sub {
19 my $res = shift;
20  
21 my ($matched, $route) = $self->router->routematch($env);
22 $matched or return;
23  
24 my $plack_res = Plack::Response->new(@$res);
25 my $body;
26 Plack::Util::foreach($res->[2] // [], sub { $body .= $_[0] });
27  
28 my $validator = APISchema::Validator->for_response(
29 validator_class => $self->validator // DEFAULT_VALIDATOR_CLASS,
30 );
31 my $result = $validator->validate($route->name => {
32 status_code => $res->[0],
33 header => +{ map {
34 my $field = lc($_) =~ s/[-]/_/gr;
35 ( $field => $plack_res->header($_) );
36 } $plack_res->headers->header_field_names },
37 body => $body,
38 content_type => scalar $plack_res->content_type,
39 }, $self->schema);
40  
41 my $errors = $result->errors;
42 if (scalar keys %$errors) {
43 @$res = (
44 500,
45 [ 'Content-Type' => 'application/json' ],
46 [ encode_json($errors) ],
47 );
48 return;
49 }
50  
51 $res->[2] = [ $body ];
52 });
53 }
54  
55 sub router {
56 my ($self) = @_;
57  
58 $self->{router} //= do {
59 my $generator = APISchema::Generator::Router::Simple->new;
60 $generator->generate_router($self->schema);
61 };
62 }
63  
64  
65 1;