package Plack::Middleware::ValidateJSON;

use strict;
use warnings;

use parent qw( Plack::Middleware );

use JSON::MaybeXS;
use Plack::Request;

# ABSTRACT: Checks validity of JSON POST'd to a Plack app and generates an error response if the JSON is not valid

=head1 NAME

Plack::Middleware::ValidateJSON

=head1 DESCRIPTION

Check validity of JSON POST'ed to the app and generate a 422 HTTP response if the JSON is not valid

=head1 PUBLIC METHODS

=head2 call

See POD for Plack::Middleware for specs.  Returns an HTTP 422 response in the event of invalid JSON.

=cut

sub call {
    my($self, $env) = @_;

    my $request = Plack::Request->new($env);

    # if content is present, make certain that it is valid JSON, otherwise there is nothing to check
    if ( $request->content_length ) {
        eval{ decode_json( $request->content); };
        if ($@) {
            my $body = 'Invalid JSON';

	    return [
		    422,
		    [ 'Content-type', 'text/plain',
		      'Content-length', length $body 
		    ],
		    [ $body ]
		   ];
        }
    }

    return $self->app->($env);
}

1;
