blib/lib/API/Client.pm untested

filter: Statementstmt 0.0% 0 / 131 Branchbran 0.0% 0 / 32 Conditioncond 0.0% 0 / 20 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 11 Podpod n/a totaltotal 0.0% 0 / 194 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package API::Client;
2  
3 use 5.014;
4  
5 use strict;
6 use warnings;
7  
8 use registry;
9 use routines;
10  
11 use Data::Object::Class;
12 use Data::Object::ClassHas;
13 use FlightRecorder;
14 use Mojo::Transaction;
15 use Mojo::UserAgent;
16 use Mojo::URL;
17  
18 with 'Data::Object::Role::Buildable';
19 with 'Data::Object::Role::Stashable';
20 with 'Data::Object::Role::Throwable';
21  
22 our $VERSION = '0.10'; # VERSION
23  
24 # ATTRIBUTES
25  
26 has 'debug' => (
27 is => 'ro',
28 isa => 'Bool',
29 def => 0,
30 );
31  
32 has 'fatal' => (
33 is => 'ro',
34 isa => 'Bool',
35 def => 0,
36 );
37  
38 has 'logger' => (
39 is => 'ro',
40 isa => 'InstanceOf["FlightRecorder"]',
41 new => 1,
42 );
43  
44 fun new_logger($self) {
45 FlightRecorder->new
46 }
47  
48 has 'name' => (
49 is => 'ro',
50 isa => 'Str',
51 new => 1,
52 );
53  
54 fun new_name($self) {
55 "@{[ref($self)]} (@{[$self->version]})"
56 }
57  
58 has 'retries' => (
59 is => 'ro',
60 isa => 'Int',
61 def => 0,
62 );
63  
64 has 'timeout' => (
65 is => 'ro',
66 isa => 'Int',
67 def => 10,
68 );
69  
70 has 'url' => (
71 is => 'ro',
72 isa => 'InstanceOf["Mojo::URL"]',
73 req => 1,
74 );
75  
76 has 'user_agent' => (
77 is => 'ro',
78 isa => 'InstanceOf["Mojo::UserAgent"]',
79 new => 1,
80 );
81  
82 fun new_user_agent($self) {
83 Mojo::UserAgent->new
84 }
85  
86 has 'version' => (
87 is => 'ro',
88 isa => 'Str',
89 new => 1,
90 );
91  
92 fun new_version($self) {
93 $self->VERSION || 0.01
94 }
95  
96 # BUILD
97  
98 method build_args($args) {
99 if (!$args->{url}) {
100 $args->{url} = join('/', @{$self->base(%$args)}) if $self->can('base');
101 }
102 if (!ref $args->{url}) {
103 $args->{url} = Mojo::URL->new($args->{url}) if $args->{url};
104 }
105  
106 return $args;
107 }
108  
109 # METHODS
110  
111 method create(Any %args) {
112  
113 return $self->dispatch(%args, method => 'post');
114 }
115  
116 method delete(Any %args) {
117  
118 return $self->dispatch(%args, method => 'delete');
119 }
120  
121 method dispatch(Str :$method = 'get', Any %args) {
122 my $log = $self->logger->info("@{[uc($method)]} @{[$self->url->to_string]}");
123  
124 my $result = $self->execute(%args, method => $method);
125  
126 $log->end;
127  
128 return $result;
129 }
130  
131 method fetch(Any %args) {
132  
133 return $self->dispatch(%args, method => 'get');
134 }
135  
136 method patch(Any %args) {
137  
138 return $self->dispatch(%args, method => 'patch');
139 }
140  
141 method update(Any %args) {
142  
143 return $self->dispatch(%args, method => 'put');
144 }
145  
146 method prepare(Object $ua, Object $tx, Any %args) {
147 $self->set_auth($ua, $tx, %args);
148 $self->set_headers($ua, $tx, %args);
149 $self->set_identity($ua, $tx, %args);
150  
151 return $self;
152 }
153  
154 method process(Object $ua, Object $tx, Any %args) {
155  
156 return $self;
157 }
158  
159 method resource(Str @segments) {
160 my $object = ref($self)->new($self->serialize);
161  
162 $object->url->path(join '/', @segments) if @segments;
163  
164 return $object;
165 }
166  
167 method serialize() {
168  
169 return {
170 debug => $self->debug,
171 fatal => $self->fatal,
172 name => $self->name,
173 retries => $self->retries,
174 timeout => $self->timeout,
175 url => $self->url->to_string,
176 };
177 }
178  
179 method set_auth($ua, $tx, %args) {
180 if ($self->can('auth')) {
181 $tx->req->url->userinfo(join ':', @{$self->auth});
182 }
183  
184 return $self;
185 }
186  
187 method set_headers($ua, $tx, %args) {
188 if ($self->can('headers')) {
189 $tx->req->headers->header(@$_) for @{$self->headers};
190 } else {
191 $tx->req->headers->header('Content-Type' => 'application/json');
192 }
193  
194 return $self;
195 }
196  
197 method set_identity($ua, $tx, %args) {
198 $tx->req->headers->header('User-Agent' => $self->name);
199  
200 return $self;
201 }
202  
203 method execute(Str :$method = 'get', Str :$path = '', Any %args) {
204 delete $args{method};
205  
206 my $ua = $self->user_agent;
207 my $url = $self->url->clone;
208  
209 my $query = $args{query} || {};
210 my $headers = $args{headers} || {};
211  
212 $url->path(join '/', $url->path, $path) if $path;
213 $url->query($url->query->merge(%$query)) if keys %$query;
214  
215 my @args;
216  
217 # data handlers
218 for my $type (sort keys %{$ua->transactor->generators}) {
219 push @args, $type, delete $args{$type} if $args{$type};
220 }
221  
222 # handle raw body value
223 push @args, delete $args{body} if exists $args{body};
224  
225 # transaction prepare hook
226 $ua->on(prepare => fun ($ua, $tx) {
227 $self->prepare($ua, $tx, %args);
228 });
229  
230 # client timeouts
231 $ua->max_redirects(0);
232 $ua->connect_timeout($self->timeout);
233 $ua->request_timeout($self->timeout);
234  
235 # transaction
236 my ($ok, $tx, $req, $res);
237  
238 # times to retry failures
239 my $retries = $self->retries;
240  
241 # transaction retry loop
242 for (my $i = 0; $i < ($retries || 1); $i++) {
243 # execute transaction
244 $tx = $ua->start($ua->build_tx($method, $url, $headers, @args));
245 $self->process($ua, $tx, %args);
246  
247 # transaction objects
248 $req = $tx->req;
249 $res = $tx->res;
250  
251 # determine success/failure
252 $ok = $res->code ? $res->code !~ /(4|5)\d\d/ : 0;
253  
254 # log activity
255 if ($req && $res) {
256 my $log = $self->logger;
257 my $msg = join " ", "attempt", ("#".($i+1)), ": $method", $url->to_string;
258  
259 $log->debug("req: $msg")->data({
260 request => $req->to_string =~ s/\s*$/\n\n\n/r
261 });
262  
263 $log->debug("res: $msg")->data({
264 response => $res->to_string =~ s/\s*$/\n\n\n/r
265 });
266  
267 # output to the console where applicable
268 $log->info("res: $msg [@{[$res->code]}]");
269 $log->output if $self->debug;
270 }
271  
272 # no retry necessary
273 last if $ok;
274 }
275  
276 # throw exception if fatal is truthy
277 if ($req && $res && $self->fatal && !$ok) {
278 my $code = $res->code;
279  
280 $self->stash(tx => $tx);
281 $self->throw([$code, uc "${code}_http_response"]);
282 }
283  
284 # return transaction
285 return $tx;
286 }
287  
288 1;
289  
290 =encoding utf8
291  
292 =head1 NAME
293  
294 API::Client
295  
296 =cut
297  
298 =head1 ABSTRACT
299  
300 HTTP API Thin-Client Abstraction
301  
302 =cut
303  
304 =head1 SYNOPSIS
305  
306 package main;
307  
308 use API::Client;
309  
310 my $client = API::Client->new(url => 'https://httpbin.org');
311  
312 # $client->resource('post');
313  
314 # $client->update(json => {...});
315  
316 =cut
317  
318 =head1 DESCRIPTION
319  
320 This package provides an abstraction and method for rapidly developing HTTP API
321 clients.
322  
323 =cut
324  
325 =head1 INTEGRATES
326  
327 This package integrates behaviors from:
328  
329 L<Data::Object::Role::Buildable>
330  
331 L<Data::Object::Role::Stashable>
332  
333 L<Data::Object::Role::Throwable>
334  
335 =cut
336  
337 =head1 LIBRARIES
338  
339 This package uses type constraints from:
340  
341 L<Types::Standard>
342  
343 =cut
344  
345 =head1 ATTRIBUTES
346  
347 This package has the following attributes:
348  
349 =cut
350  
351 =head2 debug
352  
353 debug(Bool)
354  
355 This attribute is read-only, accepts C<(Bool)> values, and is optional.
356  
357 =cut
358  
359 =head2 fatal
360  
361 fatal(Bool)
362  
363 This attribute is read-only, accepts C<(Bool)> values, and is optional.
364  
365 =cut
366  
367 =head2 logger
368  
369 logger(InstanceOf["FlightRecorder"])
370  
371 This attribute is read-only, accepts C<(InstanceOf["FlightRecorder"])> values, and is optional.
372  
373 =cut
374  
375 =head2 name
376  
377 name(Str)
378  
379 This attribute is read-only, accepts C<(Str)> values, and is optional.
380  
381 =cut
382  
383 =head2 retries
384  
385 retries(Int)
386  
387 This attribute is read-only, accepts C<(Int)> values, and is optional.
388  
389 =cut
390  
391 =head2 timeout
392  
393 timeout(Int)
394  
395 This attribute is read-only, accepts C<(Int)> values, and is optional.
396  
397 =cut
398  
399 =head2 url
400  
401 url(InstanceOf["Mojo::URL"])
402  
403 This attribute is read-only, accepts C<(InstanceOf["Mojo::URL"])> values, and is optional.
404  
405 =cut
406  
407 =head2 user_agent
408  
409 user_agent(InstanceOf["Mojo::UserAgent"])
410  
411 This attribute is read-only, accepts C<(InstanceOf["Mojo::UserAgent"])> values, and is optional.
412  
413 =cut
414  
415 =head2 version
416  
417 version(Str)
418  
419 This attribute is read-only, accepts C<(Str)> values, and is optional.
420  
421 =cut
422  
423 =head1 METHODS
424  
425 This package implements the following methods:
426  
427 =cut
428  
429 =head2 create
430  
431 create(Any %args) : InstanceOf["Mojo::Transaction"]
432  
433 The create method issues a C<POST> request to the API resource represented by
434 the object.
435  
436 =over 4
437  
438 =item create example #1
439  
440 # given: synopsis
441  
442 $client->resource('post')->create(
443 json => {active => 1}
444 );
445  
446 =back
447  
448 =cut
449  
450 =head2 delete
451  
452 delete(Any %args) : InstanceOf["Mojo::Transaction"]
453  
454 The delete method issues a C<DELETE> request to the API resource represented by
455 the object.
456  
457 =over 4
458  
459 =item delete example #1
460  
461 # given: synopsis
462  
463 $client->resource('delete')->delete;
464  
465 =back
466  
467 =cut
468  
469 =head2 dispatch
470  
471 dispatch(Str :$method = 'get', Any %args) : InstanceOf["Mojo::Transaction"]
472  
473 The dispatch method issues a request to the API resource represented by the
474 object.
475  
476 =over 4
477  
478 =item dispatch example #1
479  
480 # given: synopsis
481  
482 $client->resource('get')->dispatch;
483  
484 =back
485  
486 =over 4
487  
488 =item dispatch example #2
489  
490 # given: synopsis
491  
492 $client->resource('post')->dispatch(
493 method => 'post', body => 'active=1'
494 );
495  
496 =back
497  
498 =over 4
499  
500 =item dispatch example #3
501  
502 # given: synopsis
503  
504 $client->resource('get')->dispatch(
505 method => 'get', query => {active => 1}
506 );
507  
508 =back
509  
510 =over 4
511  
512 =item dispatch example #4
513  
514 # given: synopsis
515  
516 $client->resource('post')->dispatch(
517 method => 'post', json => {active => 1}
518 );
519  
520 =back
521  
522 =over 4
523  
524 =item dispatch example #5
525  
526 # given: synopsis
527  
528 $client->resource('post')->dispatch(
529 method => 'post', form => {active => 1}
530 );
531  
532 =back
533  
534 =over 4
535  
536 =item dispatch example #6
537  
538 # given: synopsis
539  
540 $client->resource('put')->dispatch(
541 method => 'put', json => {active => 1}
542 );
543  
544 =back
545  
546 =over 4
547  
548 =item dispatch example #7
549  
550 # given: synopsis
551  
552 $client->resource('patch')->dispatch(
553 method => 'patch', json => {active => 1}
554 );
555  
556 =back
557  
558 =over 4
559  
560 =item dispatch example #8
561  
562 # given: synopsis
563  
564 $client->resource('delete')->dispatch(
565 method => 'delete', json => {active => 1}
566 );
567  
568 =back
569  
570 =cut
571  
572 =head2 fetch
573  
574 fetch(Any %args) : InstanceOf["Mojo::Transaction"]
575  
576 The fetch method issues a C<GET> request to the API resource represented by the
577 object.
578  
579 =over 4
580  
581 =item fetch example #1
582  
583 # given: synopsis
584  
585 $client->resource('get')->fetch;
586  
587 =back
588  
589 =cut
590  
591 =head2 patch
592  
593 patch(Any %args) : InstanceOf["Mojo::Transaction"]
594  
595 The patch method issues a C<PATCH> request to the API resource represented by
596 the object.
597  
598 =over 4
599  
600 =item patch example #1
601  
602 # given: synopsis
603  
604 $client->resource('patch')->patch(
605 json => {active => 1}
606 );
607  
608 =back
609  
610 =cut
611  
612 =head2 prepare
613  
614 prepare(Object $ua, Object $tx, Any %args) : Object
615  
616 The prepare method acts as a C<before> hook triggered before each request where
617 you can modify the transactor objects.
618  
619 =over 4
620  
621 =item prepare example #1
622  
623 # given: synopsis
624  
625 require Mojo::UserAgent;
626 require Mojo::Transaction::HTTP;
627  
628 $client->prepare(
629 Mojo::UserAgent->new,
630 Mojo::Transaction::HTTP->new
631 );
632  
633 =back
634  
635 =cut
636  
637 =head2 process
638  
639 process(Object $ua, Object $tx, Any %args) : Object
640  
641 The process method acts as an C<after> hook triggered after each response where
642 you can modify the transactor objects.
643  
644 =over 4
645  
646 =item process example #1
647  
648 # given: synopsis
649  
650 require Mojo::UserAgent;
651 require Mojo::Transaction::HTTP;
652  
653 $client->process(
654 Mojo::UserAgent->new,
655 Mojo::Transaction::HTTP->new
656 );
657  
658 =back
659  
660 =cut
661  
662 =head2 resource
663  
664 resource(Str @segments) : Object
665  
666 The resource method returns a new instance of the object for the API resource
667 endpoint specified.
668  
669 =over 4
670  
671 =item resource example #1
672  
673 # given: synopsis
674  
675 $client->resource('status', 200);
676  
677 =back
678  
679 =cut
680  
681 =head2 serialize
682  
683 serialize() : HashRef
684  
685 The serialize method serializes and returns the object as a C<hashref>.
686  
687 =over 4
688  
689 =item serialize example #1
690  
691 # given: synopsis
692  
693 $client->serialize;
694  
695 =back
696  
697 =cut
698  
699 =head2 update
700  
701 update(Any %args) : InstanceOf["Mojo::Transaction"]
702  
703 The update method issues a C<PUT> request to the API resource represented by
704 the object.
705  
706 =over 4
707  
708 =item update example #1
709  
710 # given: synopsis
711  
712 $client->resource('put')->update(
713 json => {active => 1}
714 );
715  
716 =back
717  
718 =cut
719  
720 =head1 AUTHOR
721  
722 Al Newkirk, C<awncorp@cpan.org>
723  
724 =head1 LICENSE
725  
726 Copyright (C) 2011-2019, Al Newkirk, et al.
727  
728 This is free software; you can redistribute it and/or modify it under the terms
729 of the The Apache License, Version 2.0, as elucidated in the L<"license
730 file"|https://github.com/iamalnewkirk/api-client/blob/master/LICENSE>.
731  
732 =head1 PROJECT
733  
734 L<Wiki|https://github.com/iamalnewkirk/api-client/wiki>
735  
736 L<Project|https://github.com/iamalnewkirk/api-client>
737  
738 L<Initiatives|https://github.com/iamalnewkirk/api-client/projects>
739  
740 L<Milestones|https://github.com/iamalnewkirk/api-client/milestones>
741  
742 L<Contributing|https://github.com/iamalnewkirk/api-client/blob/master/CONTRIBUTE.md>
743  
744 L<Issues|https://github.com/iamalnewkirk/api-client/issues>
745  
746 =cut