| 1 | package Plack::Middleware::ValidateJSON; | ||||||||||
| 2 | |||||||||||
| 3 | 1 | ▶ | use strict; | ||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||
| 4 | 1 | ▶ | use warnings; | ||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||
| 5 | |||||||||||
| 6 | 1 | ▶ | use parent qw( Plack::Middleware ); | ||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||
| 7 | |||||||||||
| 8 | 1 | ▶ | use JSON::MaybeXS; | ||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||
| 9 | 1 | ▶ | use Plack::Request; | ||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||
| 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 | 2 | ▶ | sub call { | ||||||||
|
Subroutine
call: called CC=3 SCAR=11.0
Pod
documented
| |||||||||||
| 30 | 2 | my($self, $env) = @_; | |||||||||
| 31 | |||||||||||
| 32 | 2 | 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 | ▶ | if ( $request->content_length ) { | ||||||||
|
Branch: 1 branch
| |||||||||||
| 36 | 2 | eval{ decode_json( $request->content); }; | |||||||||
| 37 | 2 | ▶ | if ($@) { | ||||||||
|
Branch: 1 branch
| |||||||||||
| 38 | 1 | my $body = 'Invalid JSON'; | |||||||||
| 39 | |||||||||||
| 40 | return [ | ||||||||||
| 41 | 1 | 422, | |||||||||
| 42 | [ 'Content-type', 'text/plain', | ||||||||||
| 43 | 'Content-length', length $body | ||||||||||
| 44 | ], | ||||||||||
| 45 | [ $body ] | ||||||||||
| 46 | ]; | ||||||||||
| 47 | } | ||||||||||
| 48 | } | ||||||||||
| 49 | |||||||||||
| 50 | 1 | return $self->app->($env); | |||||||||
| 51 | } | ||||||||||
| 52 | |||||||||||
| 53 | 1 | 1; | |||||||||