| 1 | package Plack::Middleware::APISchema::RequestValidator; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | |||
| 5 | use parent qw(Plack::Middleware); | ||
| 6 | use HTTP::Status qw(:constants); | ||
| 7 | use Plack::Util::Accessor qw(schema validator); | ||
| 8 | use Plack::Request; | ||
| 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 | my $req = Plack::Request->new($env); | ||
| 18 | |||
| 19 | my ($matched, $route) = $self->router->routematch($env); | ||
| 20 | $matched or return $self->app->($env); | ||
| 21 | |||
| 22 | my $validator = APISchema::Validator->for_request( | ||
| 23 | validator_class => $self->validator // DEFAULT_VALIDATOR_CLASS, | ||
| 24 | ); | ||
| 25 | my $result = $validator->validate($route->name => { | ||
| 26 | header => +{ map { | ||
| 27 | my $field = lc($_) =~ s/[-]/_/gr; | ||
| 28 | ( $field => $req->header($_) ); | ||
| 29 | } $req->headers->header_field_names }, | ||
| 30 | parameter => $env->{QUERY_STRING}, | ||
| 31 | body => $req->content, | ||
| 32 | content_type => $req->content_type, | ||
| 33 | }, $self->schema); | ||
| 34 | |||
| 35 | my $errors = $result->errors; | ||
| 36 | my $status_code = $self->_resolve_status_code($result); | ||
| 37 | return [ | ||
| 38 | $status_code, | ||
| 39 | [ 'Content-Type' => 'application/json' ], | ||
| 40 | [ encode_json_canonical($errors) ], | ||
| 41 | ] if scalar keys %$errors; | ||
| 42 | |||
| 43 | $self->app->($env); | ||
| 44 | } | ||
| 45 | |||
| 46 | sub router { | ||
| 47 | my ($self) = @_; | ||
| 48 | |||
| 49 | $self->{router} //= do { | ||
| 50 | my $generator = APISchema::Generator::Router::Simple->new; | ||
| 51 | $generator->generate_router($self->schema); | ||
| 52 | }; | ||
| 53 | } | ||
| 54 | |||
| 55 | sub _resolve_status_code { | ||
| 56 | my ($self, $validation_result) = @_; | ||
| 57 | my $error_message = $validation_result->errors->{body}->{message} // ''; | ||
| 58 | return $error_message =~ m/Wrong content-type/ ? HTTP_UNSUPPORTED_MEDIA_TYPE : HTTP_UNPROCESSABLE_ENTITY; | ||
| 59 | } | ||
| 60 | |||
| 61 | |||
| 62 | 1; |