Commit | Line | Data |
256c894f |
1 | package Catalyst::Controller::REST; |
2 | |
3 | use strict; |
4 | use warnings; |
5 | use base 'Catalyst::Controller'; |
5511d1ff |
6 | use 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 |
21 | sub begin : ActionClass('Deserialize') {} |
22 | |
23 | sub 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 |
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 | ); |
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 | |
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 | |
cc186a5b |
64 | sub 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); |
74 | $c->response->content_type('text/plain'); |
75 | $c->response->body($p{'message'}); |
76 | return 1; |
77 | } |
78 | |
bb4130f6 |
79 | sub 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); |
7d2ac607 |
89 | $c->response->content_type('text/plain'); |
bb4130f6 |
90 | $c->response->body($p{'message'}); |
91 | return 1; |
92 | } |
93 | |
94 | sub _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 | |
104 | 1; |