Changed the 4xx status helpers to return error objects
[catagits/Catalyst-Action-REST.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);
bdc54939 74 $self->_set_entity($c, { error => $p{'message'} });
cc186a5b 75 return 1;
76}
77
bb4130f6 78sub status_not_found {
79 my $self = shift;
80 my $c = shift;
81 my %p = validate(@_,
82 {
83 message => { type => SCALAR },
84 },
85 );
86
87 $c->response->status(404);
bdc54939 88 $self->_set_entity($c, { error => $p{'message'} });
bb4130f6 89 return 1;
90}
91
92sub _set_entity {
93 my $self = shift;
94 my $c = shift;
95 my $entity = shift;
96 if (defined($entity)) {
97 $c->stash->{$self->config->{'serialize'}->{'stash_key'}} = $entity;
5511d1ff 98 }
99 return 1;
eccb2137 100}
256c894f 101
1021;