Added logging to 4xx status handlers
[catagits/Catalyst-Action-Serialize-Data-Serializer.git] / lib / Catalyst / Controller / REST.pm
CommitLineData
256c894f 1package Catalyst::Controller::REST;
2
3use strict;
4use warnings;
5use base 'Catalyst::Controller';
5511d1ff 6use Params::Validate qw(:all);
256c894f 7
8__PACKAGE__->mk_accessors(qw(serialize));
9
10__PACKAGE__->config(
11 serialize => {
eccb2137 12 'default' => 'YAML',
256c894f 13 'stash_key' => 'rest',
eccb2137 14 'map' => {
15 'text/x-yaml' => 'YAML',
7ad87df9 16 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
17 },
256c894f 18 }
19);
20
5511d1ff 21sub begin : ActionClass('Deserialize') {}
22
23sub end : ActionClass('Serialize') { }
24
bb4130f6 25# You probably want to refer to the HTTP 1.1 Spec for these; they should
26# conform as much as possible.
27#
28# ftp://ftp.isi.edu/in-notes/rfc2616.txt
29
5511d1ff 30sub status_created {
31 my $self = shift;
32 my $c = shift;
33 my %p = validate(@_,
34 {
35 location => { type => SCALAR | OBJECT },
36 entity => { optional => 1 },
37 },
38 );
256c894f 39
5511d1ff 40 my $location;
41 if (ref($p{'location'})) {
42 $location = $p{'location'}->as_string;
43 }
44 $c->response->status(201);
45 $c->response->header('Location' => $location);
bb4130f6 46 $self->_set_entity($c, $p{'entity'});
47 return 1;
48}
49
50sub status_ok {
51 my $self = shift;
52 my $c = shift;
53 my %p = validate(@_,
54 {
55 entity => 1,
56 },
57 );
58
59 $c->response->status(200);
60 $self->_set_entity($c, $p{'entity'});
61 return 1;
62}
63
cc186a5b 64sub status_bad_request {
65 my $self = shift;
66 my $c = shift;
67 my %p = validate(@_,
68 {
69 message => { type => SCALAR },
70 },
71 );
72
73 $c->response->status(400);
edab9038 74 $c->log->debug("Status Bad Request: " . $p{'message'});
bdc54939 75 $self->_set_entity($c, { error => $p{'message'} });
cc186a5b 76 return 1;
77}
78
bb4130f6 79sub status_not_found {
80 my $self = shift;
81 my $c = shift;
82 my %p = validate(@_,
83 {
84 message => { type => SCALAR },
85 },
86 );
87
88 $c->response->status(404);
edab9038 89 $c->log->debug("Status Not Found: " . $p{'message'});
bdc54939 90 $self->_set_entity($c, { error => $p{'message'} });
bb4130f6 91 return 1;
92}
93
94sub _set_entity {
95 my $self = shift;
96 my $c = shift;
97 my $entity = shift;
98 if (defined($entity)) {
99 $c->stash->{$self->config->{'serialize'}->{'stash_key'}} = $entity;
5511d1ff 100 }
101 return 1;
eccb2137 102}
256c894f 103
1041;