| 1 | package WebService::Async::UserAgent::MojoUA; | ||
| 2 | $WebService::Async::UserAgent::MojoUA::VERSION = '0.005'; | ||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use parent qw(WebService::Async::UserAgent); | ||
| 7 | |||
| 8 | =head1 NAME | ||
| 9 | |||
| 10 | WebService::Async::UserAgent::MojoUA - make requests using L<Mojo::UserAgent> | ||
| 11 | |||
| 12 | =head1 VERSION | ||
| 13 | |||
| 14 | version 0.005 | ||
| 15 | |||
| 16 | =head1 DESCRIPTION | ||
| 17 | |||
| 18 | Provides a L</request> method which will use L<Mojo::UA> to make | ||
| 19 | requests and return a L<Future> containing the result. Used internally by | ||
| 20 | L<WebService::Async::UserAgent>. | ||
| 21 | |||
| 22 | =cut | ||
| 23 | |||
| 24 | use Future; | ||
| 25 | use Mojo::UserAgent; | ||
| 26 | use Future::Mojo; | ||
| 27 | |||
| 28 | =head2 new | ||
| 29 | |||
| 30 | Instantiate. | ||
| 31 | |||
| 32 | =cut | ||
| 33 | |||
| 34 | sub new { my $class = shift; bless {@_}, $class } | ||
| 35 | |||
| 36 | =head2 request | ||
| 37 | |||
| 38 | Issues the request. Expects a single L<HTTP::Request> object, | ||
| 39 | and returns a L<Future> which will resolve to the decoded | ||
| 40 | response content on success, or the failure reason on failure. | ||
| 41 | |||
| 42 | =cut | ||
| 43 | |||
| 44 | sub request { | ||
| 45 | my $self = shift; | ||
| 46 | my $req = shift; | ||
| 47 | my $f = Future::Mojo->new; | ||
| 48 | my $method = lc $req->method; | ||
| 49 | $self->ua->$method( | ||
| 50 | ''.$req->uri => { | ||
| 51 | map {; | ||
| 52 | $_ => ''.$req->header($_) | ||
| 53 | } $req->header_field_names | ||
| 54 | }, | ||
| 55 | $req->content, | ||
| 56 | sub { | ||
| 57 | my ($ua, $tx) = @_; | ||
| 58 | if($tx->success) { | ||
| 59 | $f->done($tx->res->body); | ||
| 60 | } else { | ||
| 61 | my $err = $tx->error; | ||
| 62 | $f->fail(join(' ', @{$err}{qw(code message)}), http => $tx->res); | ||
| 63 | } | ||
| 64 | } | ||
| 65 | ); | ||
| 66 | return $f | ||
| 67 | } | ||
| 68 | |||
| 69 | =head2 ua | ||
| 70 | |||
| 71 | Returns the L<LWP::UserAgent> instance. | ||
| 72 | |||
| 73 | =cut | ||
| 74 | |||
| 75 | sub ua { shift->{ua} ||= Mojo::UserAgent->new } | ||
| 76 | |||
| 77 | 1; | ||
| 78 | |||
| 79 | =head1 AUTHOR | ||
| 80 | |||
| 81 | Tom Molesworth <TEAM@cpan.org> | ||
| 82 | |||
| 83 | =head1 LICENSE | ||
| 84 | |||
| 85 | Copyright Tom Molesworth 2012-2015. Licensed under the same terms as Perl itself. |