| 1 | package Sleep::Handler; | ||
| 2 | |||
| 3 | 2 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 2 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | |||
| 6 | 0 | ▶ | use Apache2::RequestRec; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 7 | use Apache2::Const qw/OK HTTP_METHOD_NOT_ALLOWED HTTP_OK HTTP_SEE_OTHER HTTP_NO_CONTENT/; | ||
| 8 | use Apache2::RequestIO (); | ||
| 9 | use APR::Table; | ||
| 10 | |||
| 11 | use CGI::Simple; | ||
| 12 | |||
| 13 | use Sleep::Request; | ||
| 14 | use Sleep::Routes; | ||
| 15 | |||
| 16 | sub BUILD { | ||
| 17 | my ($klass, $db, $routes) = @_; | ||
| 18 | return bless { db => $db, routes => $routes }, $klass; | ||
| 19 | } | ||
| 20 | |||
| 21 | sub handler : method { | ||
| 22 | my $self = shift; | ||
| 23 | my $r = shift; | ||
| 24 | |||
| 25 | my $db = $self->{db}; | ||
| 26 | my $routes = $self->{routes}; | ||
| 27 | |||
| 28 | my $cgi = CGI::Simple->new(); | ||
| 29 | |||
| 30 | my ($route, @vars) = $routes->resource($r->uri()); | ||
| 31 | |||
| 32 | eval "require $route->{class}"; | ||
| 33 | |||
| 34 | if ($@) { | ||
| 35 | die "Can't load '$route->{class}': $@"; | ||
| 36 | } | ||
| 37 | |||
| 38 | my $resource = $route->{class}->new({db => $db}); | ||
| 39 | |||
| 40 | my $request = Sleep::Request->new($r, $db, @vars); | ||
| 41 | |||
| 42 | my $method = lc $r->method(); | ||
| 43 | |||
| 44 | my $mime_type = 'application/json'; | ||
| 45 | |||
| 46 | if ($method =~ m/^get|post|put|delete$/) { | ||
| 47 | if ($method eq 'get') { | ||
| 48 | my $response = $resource->get($request); | ||
| 49 | $r->content_type($mime_type); | ||
| 50 | $r->print($response->encode($mime_type)); | ||
| 51 | return Apache2::Const::OK; | ||
| 52 | } | ||
| 53 | elsif ($method eq 'post') { | ||
| 54 | my $postdata = $cgi->param('POSTDATA'); | ||
| 55 | $request->decode($postdata); | ||
| 56 | my $response = $resource->post($request); | ||
| 57 | |||
| 58 | $r->content_type($mime_type); | ||
| 59 | $r->status(Apache2::Const::HTTP_SEE_OTHER); | ||
| 60 | $r->headers_out->{Location} = $response->location(); | ||
| 61 | return Apache2::Const::OK; | ||
| 62 | } | ||
| 63 | elsif ($method eq 'put') { | ||
| 64 | my $postdata = $cgi->param('PUTDATA'); | ||
| 65 | $request->decode($postdata); | ||
| 66 | my $response = $resource->put($request); | ||
| 67 | $r->status(Apache2::Const::HTTP_OK); | ||
| 68 | $r->content_type($mime_type); | ||
| 69 | $r->print($response->encode($mime_type)); | ||
| 70 | return Apache2::Const::OK; | ||
| 71 | } | ||
| 72 | elsif ($method eq 'delete') { | ||
| 73 | my $response = $resource->delete($request); | ||
| 74 | $r->status(Apache2::Const::HTTP_NO_CONTENT); | ||
| 75 | return Apache2::Const::OK; | ||
| 76 | } | ||
| 77 | } | ||
| 78 | |||
| 79 | return Apache2::Const::HTTP_METHOD_NOT_ALLOWED; | ||
| 80 | } | ||
| 81 | |||
| 82 | 1; | ||
| 83 | |||
| 84 | __END__ | ||