diff options
Diffstat (limited to 'lib/Narwhal/RouteBuilder/HTTPMethod.pm')
-rw-r--r-- | lib/Narwhal/RouteBuilder/HTTPMethod.pm | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/lib/Narwhal/RouteBuilder/HTTPMethod.pm b/lib/Narwhal/RouteBuilder/HTTPMethod.pm new file mode 100644 index 0000000..fb2f124 --- /dev/null +++ b/lib/Narwhal/RouteBuilder/HTTPMethod.pm @@ -0,0 +1,64 @@ +package Narwhal::RouteBuilder::HTTPMethod; +use Moose; + +with 'OX::RouteBuilder'; + +sub import { + my $meta = Class::MOP::class_of(caller); + $meta->add_route_builder( + class => __PACKAGE__, + route_spec => sub { + my $spec = shift; + return if ref($spec) || $spec !~ /^\w+$/; + return { + action => $spec, + }; + }, + ); +} + +sub compile_routes { + my $self = shift; + + my $spec = $self->route_spec; + my $params = $self->params; + + my ($defaults, $validations) = $self->extract_defaults_and_validations($params); + $defaults = { %$spec, %$defaults }; + + my $s = $self->service; + + return [ + $self->path, + defaults => $defaults, + target => sub { + my ($req) = @_; + + my %match = %{ $req->env->{'plack.router.match'}->mapping }; + my $a = $match{action}; + my $component = $s->get_dependency($a)->get; + my $method = lc($req->method); + + if ($component->can($method)) { + return $component->$method(@_); + } + elsif ($component->can('any')) { + return $component->any(@_); + } + else { + return [ + 500, + [], + ["Component $component has no method $method"] + ]; + } + + }, + validations => $validations, + ]; +} + +__PACKAGE__->meta->make_immutable; +no Moose; + +1; |