Added more status_ actions
[catagits/Catalyst-Action-REST.git] / lib / Catalyst / Controller / REST.pm
1 package Catalyst::Controller::REST;
2
3 use strict;
4 use warnings;
5 use base 'Catalyst::Controller';
6 use Params::Validate qw(:all);
7
8 __PACKAGE__->mk_accessors(qw(serialize));
9
10 __PACKAGE__->config(
11     serialize => {
12         'default'   => 'YAML',
13         'stash_key' => 'rest',
14         'map'       => {
15             'text/x-yaml'        => 'YAML',
16             'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
17         },
18     }
19 );
20
21 sub begin : ActionClass('Deserialize') {}
22
23 sub end : ActionClass('Serialize') { }
24
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
30 sub 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     );
39
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);
46     $self->_set_entity($c, $p{'entity'});
47     return 1;
48 }
49
50 sub 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
64 sub status_not_found {
65     my $self = shift;
66     my $c = shift;
67     my %p = validate(@_,
68         {
69             message => { type => SCALAR }, 
70         },
71     );
72
73     $c->response->status(404);
74     $c->response->body($p{'message'});
75     return 1;
76 }
77
78 sub _set_entity {
79     my $self = shift;
80     my $c = shift;
81     my $entity = shift;
82     if (defined($entity)) {
83         $c->stash->{$self->config->{'serialize'}->{'stash_key'}} = $entity;
84     }
85     return 1;
86 }
87
88 1;