File Coverage

blib/lib/Plack/Middleware/ValidateJSON.pm
Criterion Covered Total %
statement 24 24 100.0
branch 3 4 75.0
condition n/a
subroutine 6 6 100.0
pod 1 1 100.0
total 34 35 97.1


line stmt bran cond sub pod time code
1             package Plack::Middleware::ValidateJSON;
2              
3 1     1   58579 use strict;
  1         3  
  1         27  
4 1     1   5 use warnings;
  1         1  
  1         29  
5              
6 1     1   404 use parent qw( Plack::Middleware );
  1         274  
  1         5  
7              
8 1     1   13394 use JSON::MaybeXS;
  1         5136  
  1         70  
9 1     1   453 use Plack::Request;
  1         60465  
  1         142  
10              
11             # ABSTRACT: Checks validity of JSON POST'd to a Plack app and generates an error response if the JSON is not valid
12              
13             =head1 NAME
14              
15             Plack::Middleware::ValidateJSON
16              
17             =head1 DESCRIPTION
18              
19             Check validity of JSON POST'ed to the app and generate a 422 HTTP response if the JSON is not valid
20              
21             =head1 PUBLIC METHODS
22              
23             =head2 call
24              
25             See POD for Plack::Middleware for specs. Returns an HTTP 422 response in the event of invalid JSON.
26              
27             =cut
28              
29             sub call {
30 2     2 1 23035 my($self, $env) = @_;
31              
32 2         16 my $request = Plack::Request->new($env);
33              
34             # if content is present, make certain that it is valid JSON, otherwise there is nothing to check
35 2 50       22 if ( $request->content_length ) {
36 2         21 eval{ decode_json( $request->content); };
  2         7  
37 2 100       625 if ($@) {
38 1         4 my $body = 'Invalid JSON';
39              
40             return [
41 1         10 422,
42             [ 'Content-type', 'text/plain',
43             'Content-length', length $body
44             ],
45             [ $body ]
46             ];
47             }
48             }
49              
50 1         10 return $self->app->($env);
51             }
52              
53             1;