| 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; |