Backblaze-B2
view release on metacpan or search on metacpan
lib/Backblaze/B2/v1/AnyEvent.pm view on Meta::CPAN
if( !$body) {
$self->log_message(4, sprintf "No response body received");
@result = (0, "No response body received", $hdr);
} else {
my $b = eval { decode_json( $body ); };
if( my $err = $@ ) {
$self->log_message(4, sprintf "Error decoding JSON response body: %s", $err);
@result = (0, sprintf("Error decoding JSON response body: %s", $err), $hdr);
} elsif( $hdr->{Status} =~ /^[45]\d\d$/ ) {
my $reason = $b->{message} || $hdr->{Reason};
my $status = $b->{status} || $hdr->{Status};
$self->log_message(4, sprintf "HTTP error status: %s: %s", $status, $reason);
@result = ( 0, sprintf(sprintf "HTTP error status: %s: %s", $status, $reason));
} else {
@result = (1, "", $b);
};
};
@result
}
# Provide headers from the credentials, if available
sub get_headers {
my( $self ) = @_;
if( my $token = $self->authorizationToken ) {
return Authorization => $token
};
return ()
}
sub accountId {
my( $self ) = @_;
$self->{credentials}->{accountId}
}
sub authorizationToken {
my( $self ) = @_;
$self->{credentials}->{authorizationToken}
}
sub downloadUrl {
my( $self ) = @_;
$self->{credentials}->{downloadUrl}
}
sub apiUrl {
my( $self ) = @_;
$self->{credentials}->{apiUrl}
}
=head2 C<< ->request >>
Returns a promise that will resolve to the response data and the headers from
the request.
=cut
# You might want to override this if you want to use HIJK or
# some other way. If your HTTP requestor is synchronous, just
# return a
# AnyEvent->condvar
# which performs the real task.
# Actually, this now returns just a Promise
sub request {
my( $self, %options) = @_;
$options{ method } ||= 'GET';
#my $completed = delete $options{ cb };
my $method = delete $options{ method };
my $endpoint = delete $options{ api_endpoint };
my $headers = delete $options{ headers } || {};
$headers = { $self->get_headers, %$headers };
my $body = delete $options{ _body };
my $url;
if( ! $options{url} ) {
croak "Don't know the api_endpoint for the request"
unless $endpoint;
$url = URI->new( join( "/b2api/v1/",
$self->apiUrl,
$endpoint)
);
} else {
$url = delete $options{ url };
$url = URI->new( $url )
if( ! ref $url );
};
for my $k ( keys %options ) {
my $v = $options{ $k };
$url->query_param_append($k, $v);
};
$self->log_message(1, sprintf "Sending %s request to %s", $method, $url);
my $res = deferred;
my $req;
$req = http_request $method => $url,
headers => $headers,
body => $body,
sub {
my( $data, $headers ) = @_;
undef $req;
$res->resolve($data, $headers);
#undef $res; # justin case
},
;
$res->promise
}
=head2 C<< ->json_request >>
my $res = $b2->json_request(...)->then(sub {
my( $ok, $message, @stuff ) = @_;
});
Helper routine that expects a JSON formatted response
and returns the decoded JSON structure.
( run in 1.280 second using v1.01-cache-2.11-cpan-39bf76dae61 )