Akron | 30e7bc7 | 2021-02-16 17:05:41 +0100 | [diff] [blame] | 1 | package Kalamar::Request; |
| 2 | use Mojo::Base -base; |
| 3 | use Mojo::Promise; |
| 4 | |
| 5 | has [qw!controller ua!]; |
| 6 | |
| 7 | has url => sub { |
| 8 | my $self = shift; |
| 9 | if (@_) { |
| 10 | $self->{url} = Mojo::URL->new(shift); |
| 11 | return $self; |
| 12 | }; |
| 13 | return $self->{url}; |
| 14 | }; |
| 15 | |
| 16 | has method => sub { |
| 17 | my $self = shift; |
| 18 | if (@_) { |
| 19 | $self->{method} = uc(shift); |
| 20 | return $self; |
| 21 | }; |
| 22 | return $self->{method} // 'GET'; |
| 23 | }; |
| 24 | |
| 25 | |
| 26 | # Get or set parameters for the transaction |
| 27 | sub param { |
| 28 | my $self = shift; |
| 29 | if (scalar(@_) > 0) { |
| 30 | if (defined $_[0]) { |
| 31 | $self->{param} = [@_]; |
| 32 | } |
| 33 | else { |
| 34 | $self->{param} = undef; |
| 35 | } |
| 36 | return $self; |
| 37 | }; |
| 38 | return $self->{param} // []; |
| 39 | }; |
| 40 | |
| 41 | |
| 42 | # Start transaction and return a promise |
| 43 | sub start { |
| 44 | my $self = shift; |
| 45 | |
| 46 | # TODO: Better return a rejected promise |
| 47 | unless ($self->url) { |
| 48 | return Mojo::Promise->reject('No URL defined'); |
| 49 | }; |
| 50 | |
| 51 | unless ($self->controller) { |
| 52 | return Mojo::Promise->reject('No controller defined'); |
| 53 | }; |
| 54 | |
| 55 | unless ($self->ua) { |
| 56 | return Mojo::Promise->reject('No useragent defined'); |
| 57 | }; |
| 58 | |
| 59 | my @param = ($self->method, $self->url); |
| 60 | push @param, @{$self->param} if scalar(@{$self->param}) > 0; |
| 61 | |
| 62 | my $tx = $self->ua->build_tx(@param); |
| 63 | |
| 64 | my $c = $self->controller; |
| 65 | |
| 66 | # Set X-Forwarded for |
| 67 | if ($c->app->renderer->helpers->{'client_ip'}) { |
| 68 | $tx->req->headers->header( |
| 69 | 'X-Forwarded-For' => $c->client_ip |
| 70 | ); |
| 71 | }; |
| 72 | |
| 73 | # Emit Hook to alter request |
| 74 | $c->app->plugins->emit_hook( |
| 75 | before_korap_request => ($c, $tx) |
| 76 | ); |
| 77 | |
| 78 | # Return promise |
| 79 | return $self->ua->start_p($tx); |
| 80 | }; |
| 81 | |
| 82 | 1; |