summaryrefslogtreecommitdiffstats
path: root/lib/WWW/YNAB/UA.pm
blob: 47c9fcb683aaf6dc14f3dc7b0c8149e5df04abd7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package WWW::YNAB::UA;
use Moose;

use HTTP::Tiny;
use IO::Socket::SSL; # Necessary for https URLs on HTTP::Tiny.
use JSON::PP;
use Carp;

has access_token => (
    is       => 'ro',
    isa      => 'Str',
    required => 1,
);

has base_uri => (
    is       => 'ro',
    isa      => 'Str',
    required => 1,
);

has ua => (
    is       => 'ro',
    isa      => 'HTTP::Tiny',
    required => 1,
);

has rate_limit => (
    is        => 'ro',
    isa       => 'Int',
    writer    => '_set_rate_limit',
    predicate => 'knows_rate_limit',
);

has total_rate_limit => (
    is        => 'ro',
    isa       => 'Int',
    writer    => '_set_total_rate_limit',
    predicate => 'knows_total_rate_limit',
);

sub get {
    my $self = shift;
    $self->_request('get', @_);
}

sub post {
    my $self = shift;
    $self->_request('post', @_);
}

sub _request {
    my $self = shift;
    my ($method, $path, $params) = @_;

    if (0) {
        warn "\U$method\E $path";
    }

    my $base = $self->base_uri;
    $base =~ s{/$}{};
    $path =~ s{^/}{};
    my $uri = "$base/$path";

    my $response = $self->ua->$method(
        $uri,
        {
            ($params ? (content => encode_json($params)) : ()),
            headers => {
                'Content-Type'  => 'application/json; charset=UTF-8',
                'X-Accept'      => 'application/json',
                'Authorization' => 'Bearer ' . $self->access_token,
            },
        },
    );
    croak "Request for $uri failed ($response->{status}): $response->{content}"
        unless $response->{success};

    my $rate_limit = $response->{headers}{'x-rate-limit'};
    my ($current, $total) = split '/', $rate_limit;
    $self->_set_rate_limit($current);
    $self->_set_total_rate_limit($total);

    return decode_json($response->{content});
}

__PACKAGE__->meta->make_immutable;
no Moose;

1;