Rework ::XS serializer and deserializer classes
[catagits/Catalyst-Action-REST.git] / lib / Catalyst / Action / Deserialize / JSON.pm
1 package Catalyst::Action::Deserialize::JSON;
2
3 use Moose;
4 use namespace::autoclean;
5 use Scalar::Util qw(openhandle);
6 BEGIN {
7     $ENV{'PERL_JSON_BACKEND'} = 2; # Always use compiled JSON::XS
8 }
9
10 extends 'Catalyst::Action';
11 use JSON;
12
13 our $VERSION = '1.00';
14 $VERSION = eval $VERSION;
15
16 sub execute {
17     my $self = shift;
18     my ( $controller, $c, $test ) = @_;
19
20     my $rbody;
21
22     # could be a string or a FH
23     if ( my $body = $c->request->body ) {
24         if(openhandle $body) {
25             seek($body, 0, 0); # in case something has already read from it
26             while ( defined( my $line = <$body> ) ) {
27                 $rbody .= $line;
28             }
29         } else {
30             $rbody = $body;
31         }
32     }
33
34     if ( $rbody ) {
35         my $json = JSON->new->utf8;
36         if (my $options = $controller->{json_options}) {
37             foreach my $opt (keys %$options) {
38                 $json->$opt( $options->{$opt} );
39             }
40         }
41         my $rdata = eval { $json->decode( $rbody ) };
42         if ($@) {
43             return $@;
44         }
45         $c->request->data($rdata);
46     } else {
47         $c->log->debug(
48             'I would have deserialized, but there was nothing in the body!')
49             if $c->debug;
50     }
51     return 1;
52 }
53
54 __PACKAGE__->meta->make_immutable;
55
56 1;