WebService-MyGengo

 view release on metacpan or  search on metacpan

lib/WebService/MyGengo/Client.pm  view on Meta::CPAN

package WebService::MyGengo::Client;

use Moose;
use MooseX::NonMoose;
use namespace::autoclean;

extends qw(WebService::MyGengo::Base);

use LWP::UserAgent;
use Scalar::Util qw(blessed);
use URI;

use WebService::MyGengo;
use WebService::MyGengo::Account;
use WebService::MyGengo::Job;

use WebService::MyGengo::Comment;
use WebService::MyGengo::Feedback;
use WebService::MyGengo::Revision;

use WebService::MyGengo::Language;
use WebService::MyGengo::LanguagePair;

use WebService::MyGengo::RequestFactory;
use WebService::MyGengo::Response;
use WebService::MyGengo::Exception;

=head1 NAME

WebService::MyGengo::Client - Client for interacting with the myGengo API

=head1 DESCRIPTION

A perl library for accessing the MyGengo (L<http://mygengo.com>) API.

=head1 SYNOPSIS

    use WebService::MyGengo::Client;
    my $client = WebService::MyGengo::Client->new({
        public_key      => 'pubkey'
        , private_key   => 'privkey'
        , use_sandbox   => 1
        });

    # Alternative constructor syntax
    $client = WebService::MyGengo::Client->new('pubkey', 'privkey', $use_sandbox);

    # A WebService::MyGengo::Job
    my $job = $client->get_job( 123 );

    # Seeing what went wrong by inspecting the `last_response`
    unless ( $job = $client->get_job( "BLARGH!" ) ) {
        MyApp::Exception->throw({ message => "Oops: ".$client->last_response->message });
    }

=head1 ATTRIBUTES

All attributes are read-only unless otherwise specified.

If you need a Client with different parameters, just create a new one :)

=head2 public_key (Str)

Your public API key.

=cut
has public_key => (
    is => 'rw'
    , isa => 'Str'
    , required => 1
    , trigger => sub { shift->clear_request_factory }
    );

=head2 private_key (Str)

Your private API key.

=cut
has private_key => (
    is => 'ro'
    , isa => 'Str'
    , required => 1
    , trigger => sub { shift->clear_request_factory }
    );

=head2 use_sandbox (Bool)

A boolean flag that determines whether to use the API sandbox or the live site.

=cut
has use_sandbox => (
    is => 'ro'
    , isa => 'Bool'
    , default => 1
    , trigger => sub {
        my ( $self, $val ) = ( shift, @_ );
        $self->clear_request_factory;
        my $url = $val
                ? 'http://api.sandbox.mygengo.com/v1.1'
                : 'http://api.mygengo.com/v1.1'
                ;
        $self->_set_root_uri( URI->new( $url ) );
        }
    );

=head2 root_uri (L<URI>)

The L<URI> to be used as the base for all API endpoints.

This value is set automatically according to the L<use_sandbox> attribute.

eg, 'http://api.sandbox.mygengo.com/v1.1'

=cut
has root_uri => (
    is => 'rw'
    , isa => 'URI'
    , init_arg => undef
    , writer => '_set_root_uri'
    );

=head2 DEBUG (Bool)

A read-write flag indicating whether to dump debugging information to STDERR.

=cut
has DEBUG => (
    is          => 'rw'
    , isa       => 'Bool'
    , default   => 0
    );

=head2 _user_agent (L<LWP::UserAgent>)

This is a semi-private attribute, as most people won't use it.

You can use _set_user_agent to supply your own UserAgent object to be used
for API calls, eg L<LWPx::ParanoidAgent>.

lib/WebService/MyGengo/Client.pm  view on Meta::CPAN

    , init_arg  => undef
    );
sub _build__user_agent {
    my ( $self ) = ( shift );

    my $ua = LWP::UserAgent->new(
        agent           => $self->_user_agent_string
        , timeout       => 30
        , max_redirect  => 5
        );

    if ( $self->DEBUG ) {
        $ua->add_handler("request_send",  sub {
            print STDERR "RAW REQUEST:";
            shift->dump( maxlength => 2048 );
            print STDERR "\n";
            return;
            });
        $ua->add_handler("response_done", sub {
            print STDERR "RAW RESPONSE:";
            shift->dump( maxlength => 10000);
            print STDERR "\n";
            return;
            });
    }

    return $ua;
}

#=head2 _user_agent_string (Str)
#
#The User-Agent string reported by the client.
#
#=cut
has _user_agent_string => (
    is          => 'ro'
    , isa       => 'Str'
    , lazy      => 1
    , init_arg  => undef
    , default   => sub {
        __PACKAGE__." ".$WebService::MyGengo::VERSION
        }
    );

=head2 request_factory (L<WebService::MyGengo::RequestFactory>)

A L<WebService::MyGengo::RequestFactory> instance used to generate API requests.

=cut
has request_factory => (
    is => 'ro'
    , isa => 'WebService::MyGengo::RequestFactory'
    , lazy_build => 1
    , init_arg => undef
    );
sub _build_request_factory {
    my ( $self ) = ( shift );

    return WebService::MyGengo::RequestFactory->new({
        public_key      => $self->public_key
        , private_key   => $self->private_key
        , root_uri      => $self->root_uri
        });
}

=head2 last_response (L<WebService::MyGengo::Response>)

The last raw response object received from the API.

=cut
has last_response => (
    is => 'rw'
    , isa => 'WebService::MyGengo::Response'
    , init_arg => undef
    , writer => '_set_last_response'
    );

=head1 METHODS

Unless otherwise specified, all methods will:

=over

=item Return a true value on success

=item Return a false value on failure

=item Throw an exception on bad arguments

=item Make no effort to trap exceptions from the transport layer

=back

You can retrieve the last raw response via the `last_response` attribute to
inspect any specific error conditions. See the L<SYNOPSIS>.

=cut

#=head2 BUILDARGS
#
#Support alternative construction syntax.
#
#=cut
around BUILDARGS => sub {
    my ( $orig, $class, $args ) = ( shift, shift, @_ );

    ref($args) eq 'HASH' and return $class->$orig(@_);

    my %args;
    @args{ qw/public_key private_key use_sandbox _user_agent_string/ }
        = @_;

    return \%args;
};

=head2 get_account( )

Returns the L<WebService::MyGengo::Account> associated with your API keys.

Calls L<get_account_stats> and L<get_account_balance> internally to gather
the parameters necessary to construct the Account object.

=cut
sub get_account {
    my ($self) = @_;

    my $stats   = $self->get_account_stats();

    !( $self->last_response->is_success ) and
        WebService::MyGengo::Exception->throw({
            message => "Could not retrieve account stats"
            });

    my $balance = $self->get_account_balance();

    !( $self->last_response->is_success ) and
        WebService::MyGengo::Exception->throw({
            message => "Could not retrieve account balance"
            });

    my %args;
    @args{ keys %$stats } = values %$stats;
    @args{ keys %$balance } = values %$balance;

    return WebService::MyGengo::Account->new( \%args );
}

=head2 get_account_stats( )

Returns a reference to a hash of account statistics.

You may find it easier to simply use L<get_account>.

See: L<http://mygengo.com/api/developer-docs/methods/account-stats-get/>

=cut
sub get_account_stats {
    my ( $self ) = ( shift );
    my $res = $self->_send_request('GET', '/account/stats/');
    return $res->response_struct;
}

=head2 get_account_balance( )

Returns a reference to a hash of account balance information.

You may find it easier to simply use L<get_account>.

See: L<http://mygengo.com/api/developer-docs/methods/account-balance-get/>



( run in 2.385 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )