| 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 APISchema::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_class = $self->validator // DEFAULT_VALIDATOR_CLASS; | ||
| 29 | my $validator = APISchema::Validator->for_response( | ||
| 30 | validator_class => $validator_class, | ||
| 31 | ); | ||
| 32 | my $result = $validator->validate($route->name => { | ||
| 33 | status_code => $res->[0], | ||
| 34 | header => +{ map { | ||
| 35 | my $field = lc($_) =~ s/[-]/_/gr; | ||
| 36 | ( $field => $plack_res->header($_) ); | ||
| 37 | } $plack_res->headers->header_field_names }, | ||
| 38 | body => $body, | ||
| 39 | content_type => scalar $plack_res->content_type, | ||
| 40 | }, $self->schema); | ||
| 41 | |||
| 42 | my $errors = $result->errors; | ||
| 43 | if (scalar keys %$errors) { | ||
| 44 | my $error_cause = join '+', __PACKAGE__, $validator_class; | ||
| 45 | @$res = ( | ||
| 46 | 500, | ||
| 47 | [ 'Content-Type' => 'application/json', 'X-Error-Cause' => $error_cause ], | ||
| 48 | [ encode_json_canonical($errors) ], | ||
| 49 | ); | ||
| 50 | return; | ||
| 51 | } | ||
| 52 | |||
| 53 | $res->[2] = [ $body ]; | ||
| 54 | }); | ||
| 55 | } | ||
| 56 | |||
| 57 | sub router { | ||
| 58 | my ($self) = @_; | ||
| 59 | |||
| 60 | $self->{router} //= do { | ||
| 61 | my $generator = APISchema::Generator::Router::Simple->new; | ||
| 62 | $generator->generate_router($self->schema); | ||
| 63 | }; | ||
| 64 | } | ||
| 65 | |||
| 66 | |||
| 67 | 1; |