API-MailboxOrg

 view release on metacpan or  search on metacpan

lib/API/MailboxOrg/APIBase.pm  view on Meta::CPAN

package API::MailboxOrg::APIBase;

# ABSTRACT: Base class for all entity classes

use v5.24;

use strict;
use warnings;

use Carp;
use Moo;
use Params::ValidationCompiler qw(validation_for);
use Types::Mojo qw(:all);
use Types::Standard qw(Str Object Int);

use feature 'signatures';
no warnings 'experimental::signatures';

our $VERSION = '1.0.2'; # VERSION

has api      => ( is => 'ro', isa => Object, required => 1 );
has json_rpc => ( is => 'ro', isa => Str, default => sub { '2.0' } );

state $request_id = 1;

sub _request ( $self, $method, $params = {}, $opts = {} ) {
    my $rpc_data = {
        jsonrpc => $self->json_rpc,
        id      => $request_id++,
        method  => $method,
    };

    $rpc_data->{params} = $params->%* ? $params : "";

    my $api = $self->api;

    if ( $opts->{needs_auth} && !$api->token ) {
        my $auth_result = $api->base->auth(
            user => $api->user,
            pass => $api->password,
        );

        my $token = ref $auth_result ?
            $auth_result->{session} :
            croak 'Could not login: ' . $auth_result;

        $api->_set_token( $token );
    }

    my %header = ( 'Content-Type' => 'application/json' );
    $header{'HPLS-AUTH'} = $api->token if $api->token;

    my $uri = join '/',
        $api->host,
        $api->base_uri;

    my $tx = $api->client->post(
        $uri,
        \%header,
        json => $rpc_data,
    );

    my $response = $tx->res;

    if ( $tx->error ) {
        carp $tx->error->{message};
        return;
    }

    my $data = $response->json;

    if ( $data->{error} ) {
        carp $data->{error}->{message};
        return;
    }



( run in 1.854 second using v1.01-cache-2.11-cpan-39bf76dae61 )