b310612a49f843915d18171547a855756bac2f41
[catagits/Catalyst-Action-REST.git] / lib / Catalyst / Action / Serialize.pm
1 package Catalyst::Action::Serialize;
2
3 use Moose;
4 use namespace::autoclean;
5
6 extends 'Catalyst::Action::SerializeBase';
7 use Module::Pluggable::Object;
8 use MRO::Compat;
9
10 has _encoders => (
11    is => 'ro',
12    isa => 'HashRef',
13    default => sub { {} },
14 );
15
16 sub execute {
17     my $self = shift;
18     my ( $controller, $c ) = @_;
19
20     $self->maybe::next::method(@_);
21
22     return 1 if $c->req->method eq 'HEAD';
23     return 1 if $c->response->has_body;
24     return 1 if scalar @{ $c->error };
25     return 1 if $c->response->status =~ /^(?:204)$/;
26     return 1 if defined $c->stash->{current_view};
27     return 1 if defined $c->stash->{current_view_instance};
28
29     my ( $sclass, $sarg, $content_type ) =
30       $self->_load_content_plugins( "Catalyst::Action::Serialize",
31         $controller, $c );
32     unless ( defined($sclass) ) {
33         if ( defined($content_type) ) {
34             $c->log->info("Could not find a serializer for $content_type");
35         } else {
36             $c->log->info(
37                 "Could not find a serializer for an empty content-type");
38         }
39         return 1;
40     }
41     $c->log->debug(
42         "Serializing with $sclass" . ( $sarg ? " [$sarg]" : '' ) ) if $c->debug;
43
44     $self->_encoders->{$sclass} ||= $sclass->new;
45     my $sobj = $self->_encoders->{$sclass};
46
47     my $rc;
48     eval {
49         if ( defined($sarg) ) {
50             $rc = $sobj->execute( $controller, $c, $sarg );
51         } else {
52             $rc = $sobj->execute( $controller, $c );
53         }
54     };
55     if ($@) {
56         return $self->serialize_bad_request( $c, $content_type, $@ );
57     } elsif (!$rc) {
58         return $self->unsupported_media_type( $c, $content_type );
59     }
60
61     return 1;
62 }
63
64 __PACKAGE__->meta->make_immutable;
65
66 1;
67
68 =head1 NAME
69
70 Catalyst::Action::Serialize - Serialize Data in a Response
71
72 =head1 SYNOPSIS
73
74     package Foo::Controller::Bar;
75
76     __PACKAGE__->config(
77         'default'   => 'text/x-yaml',
78         'stash_key' => 'rest',
79         'map'       => {
80             'text/html'          => [ 'View', 'TT', ],
81             'text/x-yaml'        => 'YAML',
82             'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
83         }
84     );
85
86     sub end :ActionClass('Serialize') {}
87
88 =head1 DESCRIPTION
89
90 This action will serialize the body of an HTTP Response.  The serializer is
91 selected by introspecting the HTTP Requests content-type header.
92
93 It requires that your Catalyst controller is properly configured to set up the
94 mapping between Content Type's and Serialization classes.
95
96 The specifics of serializing each content-type is implemented as a plugin to
97 L<Catalyst::Action::Serialize>.
98
99 Typically, you would use this ActionClass on your C<end> method.  However,
100 nothing is stopping you from choosing specific methods to Serialize:
101
102   sub foo :Local :ActionClass('Serialize') {
103      .. populate stash with data ..
104   }
105
106 When you use this module, the request class will be changed to
107 L<Catalyst::Request::REST>.
108
109 =head1 CONFIGURATION
110
111 =head2 map
112
113 Takes a hashref, mapping Content-Types to a given serializer plugin.
114
115 =head2 default
116
117 This is the 'fall-back' Content-Type if none of the requested or acceptable
118 types is found in the L</map>. It must be an entry in the L</map>.
119
120 =head2 stash_key
121
122 Specifies the key of the stash entry holding the data that is to be serialized.
123 So if the value is "rest", we will serialize the data under:
124
125   $c->stash->{'rest'}
126
127 =head2 content_type_stash_key
128
129 Specifies the key of the stash entry that optionally holds an overriding
130 Content-Type. If set, and if the specified stash entry has a valid value,
131 then it takes priority over the requested content types.
132
133 This can be useful if you want to dynamically force a particular content type,
134 perhaps for debugging.
135
136 =head1 HELPFUL PEOPLE
137
138 Daisuke Maki pointed out that early versions of this Action did not play
139 well with others, or generally behave in a way that was very consistent
140 with the rest of Catalyst.
141
142 =head1 CUSTOM ERRORS
143
144 For building custom error responses when serialization fails, you can create
145 an ActionRole (and use L<Catalyst::Controller::ActionRole> to apply it to the
146 C<end> action) which overrides C<unsupported_media_type> and/or C<_serialize_bad_request>
147 methods.
148
149 =head1 SEE ALSO
150
151 You likely want to look at L<Catalyst::Controller::REST>, which implements
152 a sensible set of defaults for doing a REST controller.
153
154 L<Catalyst::Action::Deserialize>, L<Catalyst::Action::REST>
155
156 =head1 AUTHORS
157
158 See L<Catalyst::Action::REST> for authors.
159
160 =head1 LICENSE
161
162 You may distribute this code under the same terms as Perl itself.
163
164 =cut