summaryrefslogtreecommitdiffstats
path: root/lib/Narwhal/RouteBuilder/HTTPMethod.pm
blob: 33fe893d38162d2d8d6434bccd898985471cb9ae (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package Narwhal::RouteBuilder::HTTPMethod;
use Moose;

with 'OX::RouteBuilder';

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,
    ];
}

sub parse_action_spec {
    my $self = shift;
    my ($action_spec) = @_;
    return if ref($action_spec);
    return unless $action_spec =~ /^http-method:(\w+)$/;
    return {
        action => $1,
    };
}

__PACKAGE__->meta->make_immutable;
no Moose;

1;