| 1 | package Magpie::Transformer::JSON; | ||
| 2 | $Magpie::Transformer::JSON::VERSION = '1.141660'; | ||
| 3 | use Moose; | ||
| 4 | |||
| 5 | # ABSTRACT: JSON Ouput Transformer | ||
| 6 | |||
| 7 | extends 'Magpie::Transformer'; | ||
| 8 | use Scalar::Util qw(blessed); | ||
| 9 | use Magpie::Constants; | ||
| 10 | use JSON; | ||
| 11 | |||
| 12 | __PACKAGE__->register_events(qw(transform)); | ||
| 13 | |||
| 14 | sub load_queue { return qw(transform) } | ||
| 15 | |||
| 16 | sub transform { | ||
| 17 | my $self = shift; | ||
| 18 | |||
| 19 | return DECLINED if $self->resource->isa('Magpie::Resource::Abstract'); | ||
| 20 | if ( $self->resource->has_data ) { | ||
| 21 | |||
| 22 | my $data = $self->resource->data; | ||
| 23 | my $json_string = undef; | ||
| 24 | if ( blessed $data) { | ||
| 25 | if ($data->does('Data::Stream::Bulk') ) { | ||
| 26 | my @objects = (); | ||
| 27 | while ( my $block = $data->next ) { | ||
| 28 | foreach my $object (@$block) { | ||
| 29 | my $data | ||
| 30 | = $object->can('pack') ? $object->pack : {%$object}; | ||
| 31 | push @objects, JSON::encode_json($data); | ||
| 32 | } | ||
| 33 | } | ||
| 34 | $json_string = '[' . ( join ', ', @objects ) . ']'; | ||
| 35 | } | ||
| 36 | else { | ||
| 37 | $json_string = JSON->new->utf8->allow_blessed->convert_blessed->encode($data); | ||
| 38 | } | ||
| 39 | } | ||
| 40 | else { | ||
| 41 | $json_string | ||
| 42 | = JSON::encode_json($data); | ||
| 43 | } | ||
| 44 | $self->response->content_type('application/json'); | ||
| 45 | $self->response->content_length( length($json_string) ); | ||
| 46 | $self->resource->data($json_string); | ||
| 47 | } | ||
| 48 | |||
| 49 | return OK; | ||
| 50 | } | ||
| 51 | |||
| 52 | 1; | ||
| 53 | |||
| 54 | |||
| 55 | =pod | ||
| 56 | |||
| 57 | =head1 NAME | ||
| 58 | |||
| 59 | Magpie::Transformer::JSON - JSON Ouput Transformer | ||
| 60 | |||
| 61 | =head1 VERSION | ||
| 62 | |||
| 63 | version 1.141660 | ||
| 64 | |||
| 65 | =head1 AUTHORS | ||
| 66 | |||
| 67 | =over 4 | ||
| 68 | |||
| 69 | =item * | ||
| 70 | |||
| 71 | Kip Hampton <kip.hampton@tamarou.com> | ||
| 72 | |||
| 73 | =item * | ||
| 74 | |||
| 75 | Chris Prather <chris.prather@tamarou.com> | ||
| 76 | |||
| 77 | =back | ||
| 78 | |||
| 79 | =head1 COPYRIGHT AND LICENSE | ||
| 80 | |||
| 81 | This software is copyright (c) 2011 by Tamarou, LLC. | ||
| 82 | |||
| 83 | This is free software; you can redistribute it and/or modify it under | ||
| 84 | the same terms as the Perl 5 programming language system itself. | ||
| 85 | |||
| 86 | =cut | ||
| 87 | |||
| 88 | |||
| 89 | __END__ |