Client.pm untested

filter: Statementstmt 0.0% 0 / 106 Branchbran 0.0% 0 / 12 Conditioncond 0.0% 0 / 9 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 164 CC 7 SCAR 26.3
CC
7
Cov
0%
_send_ponapi_request
56.0
create
2.0
create_relationships
2.0
CRAP 13.8
1 # ABSTRACT: Client to a {JSON:API} service (http://jsonapi.org/) v1.0
2 package PONAPI::Client;
3  
4 our $VERSION = '0.002003';
5  
6 use Moose;
7  
8 use Hijk;
9 use JSON::XS qw( decode_json );
10  
11 use PONAPI::Client::Request::Create;
12 use PONAPI::Client::Request::CreateRelationships;
13 use PONAPI::Client::Request::Retrieve;
14 use PONAPI::Client::Request::RetrieveAll;
15 use PONAPI::Client::Request::RetrieveRelationships;
16 use PONAPI::Client::Request::RetrieveByRelationship;
17 use PONAPI::Client::Request::Update;
18 use PONAPI::Client::Request::UpdateRelationships;
19 use PONAPI::Client::Request::Delete;
20 use PONAPI::Client::Request::DeleteRelationships;
21  
22 has host => (
23 is => 'ro',
24 isa => 'Str',
25 default => sub { 'localhost' },
26 );
27  
28 has port => (
29 is => 'ro',
30 isa => 'Num',
31 default => sub { 5000 },
32 );
33  
34 has send_version_header => (
35 is => 'ro',
36 isa => 'Bool',
37 default => sub { 1 },
38 );
39  
40 has send_escape_values_header => (
41 is => 'ro',
42 isa => 'Bool',
43 default => sub { 1 },
44 );
45  
46  
47 ### public methods
48  
49 sub create {
50 my ( $self, @args ) = @_;
51 my $request = PONAPI::Client::Request::Create->new( @args );
52 return $self->_send_ponapi_request( $request->request_params );
53 }
54  
55 sub create_relationships {
56 my ( $self, @args ) = @_;
57 my $request = PONAPI::Client::Request::CreateRelationships->new( @args );
58 return $self->_send_ponapi_request( $request->request_params );
59 }
60  
61 sub retrieve_all {
62 my ( $self, @args ) = @_;
63 my $request = PONAPI::Client::Request::RetrieveAll->new( @args );
64 return $self->_send_ponapi_request( $request->request_params );
65 }
66  
67 sub retrieve {
68 my ( $self, @args ) = @_;
69 my $request = PONAPI::Client::Request::Retrieve->new( @args );
70 return $self->_send_ponapi_request( $request->request_params );
71 }
72  
73 sub retrieve_relationships {
74 my ( $self, @args ) = @_;
75 my $request = PONAPI::Client::Request::RetrieveRelationships->new( @args );
76 return $self->_send_ponapi_request( $request->request_params );
77 }
78  
79 sub retrieve_by_relationship {
80 my ( $self, @args ) = @_;
81 my $request = PONAPI::Client::Request::RetrieveByRelationship->new( @args );
82 return $self->_send_ponapi_request( $request->request_params );
83 }
84  
85 sub update {
86 my ( $self, @args ) = @_;
87 my $request = PONAPI::Client::Request::Update->new( @args );
88 return $self->_send_ponapi_request( $request->request_params );
89 }
90  
91 sub update_relationships {
92 my ( $self, @args ) = @_;
93 my $request = PONAPI::Client::Request::UpdateRelationships->new( @args );
94 return $self->_send_ponapi_request( $request->request_params );
95 }
96  
97 sub delete : method {
98 my ( $self, @args ) = @_;
99 my $request = PONAPI::Client::Request::Delete->new( @args );
100 return $self->_send_ponapi_request( $request->request_params );
101 }
102  
103 sub delete_relationships {
104 my ( $self, @args ) = @_;
105 my $request = PONAPI::Client::Request::DeleteRelationships->new( @args );
106 return $self->_send_ponapi_request( $request->request_params );
107 }
108  
109  
110 ### private methods
111 use constant OLD_HIJK => $Hijk::VERSION lt '0.16';
112 sub _send_ponapi_request {
113 my $self = shift;
114 my %args = @_;
115  
116 my ($status, $content, $failed, $e);
117 ($status, $content) = do {
118 local $@;
119 eval {
120 my $res = Hijk::request({
121 %args,
122 host => $self->host,
123 port => $self->port,
124 head => [
125 'Content-Type' => 'application/vnd.api+json',
126 ( $self->send_version_header
127 ? ( 'X-PONAPI-Client-Version' => '1.0' )
128 : ()
129 ),
130 ( $self->send_escape_values_header
131 ? ( 'X-PONAPI-Escaped-Values' => '1' )
132 : ()
133 ),
134 ],
135 parse_chunked => 1,
136 });
137 $status = $res->{status};
138  
139 if ( OLD_HIJK ) {
140 if ( ($res->{head}{'Transfer-Encoding'}||'') eq 'chunked' ) {
141 die "Got a chunked response from the server, but this version of Hijk can't handle those; please upgrade to at least Hijk 0.16";
142 }
143 }
144 $content = $res->{body} ? decode_json( $res->{body} ) : '';
145 1;
146 }
147 or do {
148 ($failed, $e) = (1, $@||'Unknown error');
149 };
150  
151 if ( $failed ) {
152 $status ||= 400;
153 $content = {
154 errors => [ { detail => $e, status => $status } ],
155 };
156 }
157  
158 ($status, $content);
159 };
160  
161 return ($status, $content);
162 }
163  
164 __PACKAGE__->meta->make_immutable;
165 no Moose; 1;
166  
167 __END__
168  
169 =pod
170  
171 =encoding UTF-8
172  
173 =head1 NAME
174  
175 PONAPI::Client - Client to a {JSON:API} service (http://jsonapi.org/) v1.0
176  
177 =head1 VERSION
178  
179 version 0.002003
180  
181 =head1 SYNOPSIS
182  
183 use PONAPI::Client;
184 my $client = PONAPI::Client->new(
185 host => $host,
186 port => $port,
187 );
188  
189 $client->retrieve_all( type => $type );
190  
191 $client->retrieve(
192 type => $type,
193 id => $id,
194 );
195  
196 $client->retrieve_relationships(
197 type => $type,
198 id => $id,
199 rel_type => $rel_type,
200 );
201  
202 $client->retrieve_by_relationship(
203 type => $type,
204 id => $id,
205 rel_type => $rel_type,
206 );
207  
208 $client->create(
209 type => $type,
210 data => {
211 attributes => { ... },
212 relationships => { ... },
213 },
214 );
215  
216 $client->delete(
217 type => $type,
218 id => $id,
219 );
220  
221 $client->update(
222 type => $type,
223 id => $id,
224 data => {
225 type => $type,
226 id => $id,
227 attributes => { ... },
228 relationships => { ... },
229 }
230 );
231  
232 $client->delete_relationships(
233 type => $type,
234 id => $id,
235 rel_type => $rel_type,
236 data => [
237 { type => $rel_type, id => $rel_id },
238 ...
239 ],
240 );
241  
242 $client->create_relationships(
243 type => $type,
244 id => $id,
245 rel_type => $rel_type,
246 data => [
247 { type => $rel_type, id => $rel_id },
248 ...
249 ],
250 );
251  
252 $client->update_relationships(
253 type => $type,
254 id => $id,
255 rel_type => $rel_type,
256 # for a one-to-one:
257 data => { type => $rel_type, id => $rel_id },
258 # or for a one-to-many:
259 data => [
260 { type => $rel_type, id => $rel_id },
261 ...
262 ],
263 );
264  
265 =head1 DESCRIPTION
266  
267 C<PONAPI::Client> is a L<{JSON:API}|http://jsonapi.org/> compliant client;
268 it should be able to communicate with any API-compliant service.
269  
270 The client does a handful of checks required by the spec, then uses L<Hijk>
271 to communicate with the service.
272  
273 In most cases, all API methods return a response document:
274  
275 my $response = $client->retrieve(...);
276  
277 In list context however, all api methods will return the request status and
278 the document:
279  
280 my ($status, $response) = $client->retrieve(...)
281  
282 Response documents will look something like these:
283  
284 # Successful retrieve(type => 'articles', id => 2)
285 {
286 jsonapi => { version => "1.0" },
287 links => { self => "/articles/2" },
288 data => { ... },
289 meta => { ... }, # May not be there
290 included => [ ... ], # May not be there, see C<include>
291 }
292  
293 # Successful retrieve_all( type => 'articles' )
294 {
295 jsonapi => { version => "1.0" },
296 links => { self => "/articles" }, # May include pagination links
297 data => [
298 { ... },
299 { ... },
300 ...
301 ],
302 meta => { ... }, # May not be there
303 included => [ ... ], # May not be there, see C<include>
304 }
305  
306 # Successful create(type => 'foo', data => { ... })
307 {
308 jsonapi => { version => "1.0" },
309 links => { self => "/foo/$created_id" },
310 data => { type => 'foo', id => $created_id },
311 }
312  
313 # Successful update(type => 'foo', id => 2, data => { ... })
314 {
315 jsonapi => { version => "1.0" },
316 links => { self => "/foo/2" }, # may not be there
317 meta => { ... }, # may not be there
318 }
319  
320 # Error, see http://jsonapi.org/format/#error-objects
321 {
322 jsonapi => { version => "1.0" },
323 errors => [
324 { ... }, # error 1
325 ... # potentially others
326 ],
327 }
328  
329 However, there are situations where the server may respond with a
330 C<204 No Content> and no response document; depending on the situation,
331 it might be worth checking the status.
332  
333 =for TODO Do we want to explain how to create your own subclass of the client?
334  
335 =head1 METHODS
336  
337 =head2 new
338  
339 Creates a new C<PONAPI::Client> object. Takes a couple of attributes:
340  
341 =over 4
342  
343 =item host
344  
345 The hostname (or IP address) of the service. Defaults to localhost.
346  
347 =item port
348  
349 Port of the service. Defaults to 5000.
350  
351 =item send_version_header
352  
353 Sends a C<X-PONAPI-Client-Version> header set to the {JSON:API} version the
354 client supports. Defaults to true.
355  
356 =back
357  
358 =head2 retrieve_all
359  
360 retrieve_all( type => $type, %optional_arguments )
361  
362 Retrieves B<all> resources of the given type. In SQL, this is similar to
363 C<SELECT * FROM $type>.
364  
365 This handles several arguments:
366  
367 =over 4
368  
369 =item fields
370  
371 L<Spec|http://jsonapi.org/format/#fetching-sparse-fieldsets>.
372  
373 Instead of returning every attribute and relationship from a given resource,
374 C<fields> can be used to specify exactly what is returned.
375  
376 This excepts a hashref of arrayrefs, where the keys are types, and the values
377 are either attribute names, or relationship names.
378  
379 $client->retrieve_all(
380 type => 'people',
381 fields => { people => [ 'name', 'age' ] }
382 )
383  
384 Note that an attribute not being in fields means the opposite to
385 an attribute having empty fields:
386  
387 # No attributes or relationships for both people and comments
388 $client->retrieve_all(
389 type => 'people',
390 fields => { people => [], comments => [] },
391 );
392  
393 # No attributes or relationships for comments, but
394 # ALL attributes and relationships for people
395 $client->retrieve_all(
396 type => 'people',
397 fields => { comments => [] },
398 );
399  
400 =item include
401  
402 L<Spec|http://jsonapi.org/format/#fetching-includes>.
403  
404 C<include> can be used to fetch related resources.
405 The example below is fetching both all the people, and all comments made by
406 those people:
407  
408 my $response = $client->retrieve_all(
409 type => 'people',
410 include => ['comments']
411 );
412  
413 C<include> expects an arrayref of relationship names. In the response,
414 the resources fetched will be in an arrayref under the top-level C<included>
415 key:
416  
417 say $_->{attributes}{body} for @{ $response->{included} }
418  
419 =item page
420  
421 L<Spec|http://jsonapi.org/format/#fetching-pagination>.
422  
423 Requests that the server paginate the results. Each endpoint may have different
424 pagination rules.
425  
426 =item sort
427  
428 L<Spec|http://jsonapi.org/format/#fetching-sorting>.
429  
430 Requests that the server sort the results in a given way:
431  
432 $client->retrieve_all(
433 type => 'people',
434 sort => [qw/ age /], # sort by age, ascending
435 );
436  
437 $client->retrieve_all(
438 type => 'people',
439 sort => [qw/ -age /], # sort by age, descending
440 );
441  
442 Although not all endpoints will support this, it may be possible to sort by
443 a relationship's attribute:
444  
445 $client->retrieve_all(
446 type => 'people',
447 sort => [qw/ -comments.created_date /],
448 );
449  
450 =item filter
451  
452 L<Spec|http://jsonapi.org/format/#fetching-filtering>.
453  
454 This one is entirely dependent on the endpoint. It's usually employed
455 to act as a C<WHERE> clause:
456  
457 $client->retrieve_all(
458 type => 'people',
459 filter => {
460 id => [ 1, 2, 3, 4, 6 ], # IN ( 1, 2, ... )
461 age => 34, # age = 34
462 },
463 );
464  
465 Sadly, more complex filters are currently not available.
466  
467 =back
468  
469 =head2 retrieve
470  
471 retrieve( type => $type, id => $id, %optional_arguments )
472  
473 Similar to C<retrieve_all>, but retrieves a single resource.
474  
475 =head2 retrieve_relationships
476  
477 retrieve_relationships( type => $type, id => $id, rel_type => $rel_type, %optional_arguments )
478  
479 Retrieves all of C<$id>'s relationships to C<$rel_type> as resource identifiers;
480 that is, as hashrefs that contain only C<type> and C<id>:
481  
482 # retrieve_relationships(type=>'people', id=>2, rel_type=>'comments')
483 {
484 jsonapi => { version => "1.0" },
485 data => [
486 { type => 'comments', id => 4 },
487 { type => 'comments', id => 9 },
488 { type => 'comments', id => 14 },
489 ]
490 }
491  
492 These two do roughly the same thing:
493  
494 my $response = $client->retrieve( type => $type, id => $id );
495 my $relationships = $response->{data}{relationships}{$rel_type};
496 say join ", ", map $_->{id}, @$relationships;
497  
498 my $response = $client->retrieve_relationships(
499 type => $type,
500 id => $id,
501 rel_type => $rel_type,
502 );
503 my $relationships = $response->{data};
504 say join ", ", map $_->{id}, @$relationships;
505  
506 However, C<retrieve_relationships> also allows you to page those
507 relationships, which may be quite useful.
508  
509 Keep in mind that C<retrieve_relationships> will return an arrayref for
510 one-to-many relationships, and a hashref for one-to-ones.
511  
512 =head2 retrieve_by_relationship
513  
514 retrieve_by_relationship( type => $type, id => $id, rel_type => $rel_type, %optional_arguments )
515  
516 C<retrieve_relationships> on steroids. It behaves the same way, but will
517 retrieve full resources, not just resource identifiers; because of this,
518 you can also potentially apply more complex filters and sorts.
519  
520 =head2 create
521  
522 create( type => $type, data => { ... }, id => $optional )
523  
524 Create a resource of type C<$type> using C<$data> to populate it.
525 Data B<must> include the type, and may include two other keys: C<attributes>
526 and C<relationships>:
527  
528 $client->create(
529 type => 'comments',
530 data => {
531 type => 'comments',
532 attributes => { body => 'abc' },
533 relationships => {
534 author => { type => 'people', id => 55 },
535 liked_by => [
536 { type => 'people', id => 55 },
537 { type => 'people', id => 577 },
538 ],
539 }
540 }
541 }
542  
543 An optional C<id> may be provided, in which case the server may choose to use
544 it when creating the new resource.
545  
546 =head2 update
547  
548 update( type => $type, id => $id, data => { ... } )
549  
550 Can be used to update the resource. Data B<must> have C<type> and C<id> keys:
551  
552 $client->create(
553 type => 'comments',
554 id => 5,
555 data => {
556 type => 'comments',
557 id => 5,
558 attributes => { body => 'new body!' },
559 relationships => {
560 author => undef, # no author
561 liked_by => [
562 { type => 'people', id => 79 },
563 ],
564 }
565 }
566 }
567  
568 An empty arrayref (C<[]>) can be used to clear one-to-many relationships, and
569 C<undef> to clear one-to-one relationships.
570  
571 A successful C<update> will always return a response document; see the spec
572 for more details.
573  
574 L<Spec|http://jsonapi.org/format/#crud-updating>.
575  
576 =head2 delete
577  
578 delete( type => $type, id => $id )
579  
580 Deletes the resource.
581  
582 =head2 update_relationships
583  
584 update_relationships( type => $type, id => $id, rel_type => $rel_type, data => $data )
585  
586 Update a resource's relationships. Basically a shortcut to using C<update>.
587  
588 For one-to-one relationships, C<data> can be either a single hashref, or undef.
589 For one-to-many relationships, C<data> can be an arrayref; an empty arrayref
590 means 'clear the relationship'.
591  
592 =head2 create_relationships
593  
594 create_relationships( type => $type, id => $id, rel_type => $rel_type, data => [{ ... }] )
595  
596 Adds to the specified one-to-many relationship.
597  
598 =head2 delete_relationships
599  
600 delete_relationships( type => $type, id => $id, rel_type => $rel_type, data => [{ ... }] )
601  
602 Deletes from the specified one-to-many relationship.
603  
604 =head1 AUTHORS
605  
606 =over 4
607  
608 =item *
609  
610 Mickey Nasriachi <mickey@cpan.org>
611  
612 =item *
613  
614 Stevan Little <stevan@cpan.org>
615  
616 =item *
617  
618 Brian Fraser <hugmeir@cpan.org>
619  
620 =back
621  
622 =head1 COPYRIGHT AND LICENSE
623  
624 This software is copyright (c) 2016 by Mickey Nasriachi, Stevan Little, Brian Fraser.
625  
626 This is free software; you can redistribute it and/or modify it under
627 the same terms as the Perl 5 programming language system itself.
628  
629 =cut