« blib/lib/APISchema/Validator/Result.pm
↑ Summary
blib/lib/Plack/Middleware/APISchema/ResponseValidator.pm »
| 1 | package Plack::Middleware::APISchema::RequestValidator; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | |||
| 5 | use parent qw(Plack::Middleware); | ||
| 6 | use Plack::Util::Accessor qw(schema validator status_code); | ||
| 7 | use Plack::Request; | ||
| 8 | use APISchema::Generator::Router::Simple; | ||
| 9 | use APISchema::Validator; | ||
| 10 | use JSON::XS qw(encode_json); | ||
| 11 | |||
| 12 | use constant DEFAULT_VALIDATOR_CLASS => 'Valiemon'; | ||
| 13 | |||
| 14 | sub call { | ||
| 15 | my ($self, $env) = @_; | ||
| 16 | my $req = Plack::Request->new($env); | ||
| 17 | |||
| 18 | my ($matched, $route) = $self->router->routematch($env); | ||
| 19 | $matched or return $self->app->($env); | ||
| 20 | |||
| 21 | my $validator = APISchema::Validator->for_request( | ||
| 22 | validator_class => $self->validator // DEFAULT_VALIDATOR_CLASS, | ||
| 23 | ); | ||
| 24 | my $result = $validator->validate($route->name => { | ||
| 25 | header => +{ map { | ||
| 26 | my $field = lc($_) =~ s/[-]/_/gr; | ||
| 27 | ( $field => $req->header($_) ); | ||
| 28 | } $req->headers->header_field_names }, | ||
| 29 | parameter => $env->{QUERY_STRING}, | ||
| 30 | body => $req->content, | ||
| 31 | content_type => $req->content_type, | ||
| 32 | }, $self->schema); | ||
| 33 | |||
| 34 | my $errors = $result->errors; | ||
| 35 | my $status_code = $self->status_code // 400; | ||
| 36 | return [ | ||
| 37 | $status_code, | ||
| 38 | [ 'Content-Type' => 'application/json' ], | ||
| 39 | [ encode_json($errors) ], | ||
| 40 | ] if scalar keys %$errors; | ||
| 41 | |||
| 42 | $self->app->($env); | ||
| 43 | } | ||
| 44 | |||
| 45 | sub router { | ||
| 46 | my ($self) = @_; | ||
| 47 | |||
| 48 | $self->{router} //= do { | ||
| 49 | my $generator = APISchema::Generator::Router::Simple->new; | ||
| 50 | $generator->generate_router($self->schema); | ||
| 51 | }; | ||
| 52 | } | ||
| 53 | |||
| 54 | |||
| 55 | 1; |