# Pastebin xWsBC1bY package Mojolicious::Plugin::JSON::Validator; use Mojo::Base 'Mojolicious::Plugin'; use Mojo::Loader; use JSON::Validator; our $VERSION = '0.01'; sub register { my ($self, $app, $config) = @_; my $format = $config->{format} || 'json'; my $validator = $config->{validator} || JSON::Validator->new; my $autovalid = $config->{auto_validate}; $app->helper( validate_json => sub { my $c = shift; my $data = shift || $c->req->json; my $schema = shift || $c->stash('json.validator.schema'); unless ($schema) { my ($controller, $action) = @$stash{qw(controller action)}; $schema = ($controller and $action) ? join '/', split('-', decamelize $controller), $action : 'default'; $schema .= ".spec.$format"; } return $validator->schema($schema)->validate($data); } ); $app->hook(around_action => sub { my ($next, $c, $action, $last) = @_; my $route_to = $c->match->endpoint->to; if(not $route_to->{'json.validator.schema'}) { return $next->(); } my @errors = $c->validate_json; if($autovalid eq "render") { $c->res->code = $route_to->{'json.validator.code'} || 400 if @errors; if(my $template = $route_to->{'json.validator.template_error'}) { $c->render($template) } elsif(my $inline = $route_to->{'json.validator.inline_error'}) { $c->render(inline => $inline) } else { $c->respond_to( json => {json => {errors => [@errors]}}, xml => {inline => "<% for my $err(@$errors) { %> <%= $err %> <% } %>", errors => [@errors]}, html => {inline => "", errors => [@errors]}, ) } } else { $c->$action(@errors) } }) if $autovalid; }