blib/lib/JSONAPI/Document.pm

filter: Statementstmt 98.4% 127 / 129 Branchbran 81.5% 31 / 38 Conditioncond 56.6% 17 / 30 MC/DCmcdc 21.0% 4 / 19 Subroutinesub 100% 18 / 18 Podpod 0.0% 0 / 3 totaltotal 83.1% 197 / 237 CC 36 SCAR 20.3
CC
36
Cov
89%
resource_document
17.2
_relation_with_attributes
6.3
compound_resource_document
5.0
CRAP 7.6
↑ Summary
1 package JSONAPI::Document;
2 4 $JSONAPI::Document::VERSION = '1.2';
3 # ABSTRACT: Turn DBIx results into JSON API documents.
4  
5 4 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 4 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use CHI;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use Lingua::EN::Inflexion ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 4 ▶use Lingua::EN::Segment;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 has kebab_case_attrs => (
13 is => 'ro',
14 5 ▶ default => sub { 0 }
Subroutine __ANON__: called CC=1 SCAR=0.0
15 4 );
16  
17 has attributes_via => (
18 is => 'ro',
19 4 ▶ default => sub { 'get_inflated_columns' },
Subroutine __ANON__: called CC=1 SCAR=0.0
20 4 );
21  
22 has api_url => (
23 is => 'ro',
24 isa => sub {
25 6 ▶ Carp::croak('api_url should be an absolute url') unless $_[0] =~ m/^http/;
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
unless $_[0] =~ /^http/ 0 6 6
26 },
27 4 required => 1,
28 );
29  
30 4 has data_dir => (
31 is => 'ro',
32 required => 1,
33 );
34  
35 4 has chi => (
36 is => 'lazy',
37 );
38  
39 4 has segmenter => (
40 is => 'lazy',
41 );
42  
43 sub _build_chi {
44 6 ▶ my ($self) = @_;
Subroutine _build_chi: called CC=1 SCAR=0.0
45 6 return CHI->new(driver => 'File', root_dir => $self->data_dir);
46 }
47  
48 sub _build_segmenter {
49 5 ▶ return Lingua::EN::Segment->new;
Subroutine _build_segmenter: called CC=1 SCAR=0.0
50 }
51  
52 sub compound_resource_document {
53 2 ▶ my ( $self, $row, $options ) = @_;
Subroutine compound_resource_document: called CC=5 SCAR=16.1
Pod undocumented
54  
55 2 my @relationships = $row->result_source->relationships();
56 2 ▶ if ( $options->{includes} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"includes"}) 1 1 2
57 1 @relationships = @{$options->{includes}};
58 }
59  
60 2 my $document = $self->resource_document( $row, { with_relationships => 1, includes => \@relationships } );
61  
62 2 my @included;
63 2 foreach my $relation ( sort @relationships ) {
64 3 my $result = $self->_related_resource_documents( $row, $relation, { with_attributes => 1 } );
65 3 ▶ if (my $related_docs = $result->{data}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $related_docs = $result->{"data"}) 3 0 3
66 3 ▶ if (ref($related_docs) eq 'ARRAY') { # plural relations
Branch: 1 branch
BranchTrueFalseTotal
if (ref $related_docs eq 'ARRAY') { } 1 2 3
67 1 push @included, @$related_docs;
68 } else { # singular relations
69 2 push @included, $related_docs;
70 }
71 }
72 }
73  
74 return {
75 2 data => $document,
76 included => \@included,
77 };
78 }
79  
80 sub resource_documents {
81 1 ▶ my ( $self, $resultset, $options ) = @_;
Subroutine resource_documents: called CC=2 SCAR=7.0
Pod undocumented
82 1 ▶ $options //= {};
Condition50%1/2
$options //= {}
l!l
01
MC/DC0%0/1
$options //= {}
$options
Truth table50%1/2
A
A= $options
Aresult
11
00
83  
84 1 my @results = $resultset->all();
85 1 return { data => [ map { $self->resource_document( $_, $options ) } @results ], };
86 }
87  
88 sub resource_document {
89 11 ▶ my ( $self, $row, $options ) = @_;
Subroutine resource_document: called CC=16 SCAR=28.4
Pod undocumented
90 11 ▶ Carp::confess('No row provided') unless $row;
Branch: 1 branch
BranchTrueFalseTotal
unless $row 0 11 11
91  
92 11 ▶ $options //= {};
Condition100%2/2
$options //= {}
l!l
83
MC/DC100%1/1
$options //= {}
$options
Truth table100%2/2
A
A= $options
Aresult
11
00
93 11 ▶ my $attrs_method = $options->{attributes_via} // $self->attributes_via;
Condition66%2/3
$options->{"attributes_via"} // $self->attributes_via
l!l&&r!l&&!r
1100
MC/DC0%0/2
$options->{"attributes_via"} // $self->attributes_via
$options->{"attributes_via"} $self->attributes_via
Truth table66%2/3
A // B
A= $options->{"attributes_via"}B= $self->attributes_via
ABresult
1X1
011
000
94 11 ▶ my $with_kebab_case = $options->{kebab_case_attrs} // $self->kebab_case_attrs;
Condition66%2/3
$options->{"kebab_case_attrs"} // $self->kebab_case_attrs
l!l&&r!l&&!r
029
MC/DC50%1/2
$options->{"kebab_case_attrs"} // $self->kebab_case_attrs
$options->{"kebab_case_attrs"} $self->kebab_case_attrs
Truth table66%2/3
A // B
A= $options->{"kebab_case_attrs"}B= $self->kebab_case_attrs
ABresult
1X1
011
000
95 11 my $with_attributes = $options->{with_attributes};
96 11 my $with_relationships = $options->{with_relationships};
97 11 my $includes = $options->{includes};
98  
99 11 my $type = lc( $row->result_source->source_name() );
100 11 my $noun = Lingua::EN::Inflexion::noun($type);
101  
102 11 my %columns = $row->$attrs_method();
103 11 ▶ my $id = delete $columns{id} // $row->id;
Condition66%2/3
delete $columns{"id"} // $row->id
l!l&&r!l&&!r
920
MC/DC0%0/2
delete $columns{"id"} // $row->id
delete $columns{"id"} $row->id
Truth table66%2/3
A // B
A= delete $columns{"id"}B= $row->id
ABresult
1X1
011
000
104  
105 11 ▶ unless ( $type && $id ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($type and $id) 0 11 11
Condition33%1/3
$type and $id
!ll&&!rl&&r
0011
MC/DC0%0/2
$type and $id
$type $id
Truth table33%1/3
A and B
A= $typeB= $id
ABresult
0X0
100
111
106 0 return undef; # Document is not valid without a type and id.
107 }
108  
109 11 my %relationships;
110 11 ▶ if ($with_relationships) {
Branch: 1 branch
BranchTrueFalseTotal
if ($with_relationships) 5 6 11
111 5 ▶ my @relations = $includes ? @$includes : $row->result_source->relationships();
Branch: 1 branch
BranchTrueFalseTotal
$includes ? : 4 1 5
112 5 foreach my $rel (@relations) {
113 7 ▶ if ( $row->has_relationship($rel) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($row->has_relationship($rel)) 7 0 7
114 7 ▶ if ($with_attributes) {
Branch: 1 branch
BranchTrueFalseTotal
if ($with_attributes) { } 1 6 7
115 1 $relationships{$rel} = $self->_related_resource_documents( $row, $rel, $options );
116 } else {
117 6 $relationships{$rel} = $self->_related_resource_links($row, $noun, $rel, $options);
118 }
119 }
120 }
121 }
122  
123 11 ▶ if ($with_kebab_case) {
Branch: 1 branch
BranchTrueFalseTotal
if ($with_kebab_case) 2 9 11
124 2 %columns = _kebab_case(%columns);
125 2 ▶ if ( values(%relationships) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (values %relationships) 2 0 2
126 2 %relationships = _kebab_case(%relationships);
127 }
128 }
129  
130 my $resource_type = $self->chi->compute(__PACKAGE__ . ':' . $noun->plural, undef, sub {
131 7 ▶ my @words = $self->segmenter->segment($noun->plural);
Subroutine __ANON__: called CC=2 SCAR=7.6
132 7 ▶ unless ( @words > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@words > 0) 0 7 7
133 0 @words = ($noun->plural);
134 }
135 7 return join('-', @words);
136 11 });
137  
138 11 my %document;
139  
140 11 $document{id} = $id;
141 11 $document{type} = $resource_type;
142 11 $document{attributes} = \%columns;
143  
144 11 ▶ if ( values(%relationships) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (values %relationships) 5 6 11
145 5 $document{relationships} = \%relationships;
146 }
147  
148 11 return \%document;
149 }
150  
151 sub _related_resource_links {
152 6 ▶ my ($self, $row, $row_noun, $relation, $options) = @_;
Subroutine _related_resource_links: called CC=5 SCAR=16.1
153 6 ▶ my $with_kebab_case = $options->{kebab_case_attrs} // $self->kebab_case_attrs;
Condition66%2/3
$options->{"kebab_case_attrs"} // $self->kebab_case_attrs
l!l&&r!l&&!r
015
MC/DC50%1/2
$options->{"kebab_case_attrs"} // $self->kebab_case_attrs
$options->{"kebab_case_attrs"} $self->kebab_case_attrs
Truth table66%2/3
A // B
A= $options->{"kebab_case_attrs"}B= $self->kebab_case_attrs
ABresult
1X1
011
000
154 6 my $relation_row = $row->$relation;
155 6 my $relation_type = $relation;
156  
157 6 ▶ if ($with_kebab_case) {
Branch: 1 branch
BranchTrueFalseTotal
if ($with_kebab_case) 1 5 6
158 1 $relation_type =~ s/_/-/g;
159 }
160  
161 6 my $data;
162 6 my $rel_info = $row->result_source->relationship_info($relation);
163 6 ▶ if ( $rel_info->{attrs}->{accessor} eq 'multi' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rel_info->{'attrs'}{'accessor'} eq 'multi') { } 3 3 6
164 3 $data = [];
165 3 my @rs = $relation_row->all();
166 3 foreach my $rel_row (@rs) {
167 5 push @$data, { id => $rel_row->id, type => $relation_type };
168 }
169 } else {
170 3 $data = {
171 id => $relation_row->id,
172 type => Lingua::EN::Inflexion::noun( lc($relation) )->plural,
173 };
174 }
175  
176 return {
177 6 links => {
178 self => $self->api_url . '/' . $row_noun->plural . '/' . $row->id . "/relationships/$relation_type",
179 related => $self->api_url . '/' . $row_noun->plural . '/' . $row->id . "/$relation_type",
180 },
181 data => $data,
182 };
183 }
184  
185 sub _related_resource_documents {
186 4 ▶ my ( $self, $row, $relation, $options ) = @_;
Subroutine _related_resource_documents: called CC=4 SCAR=13.9
187 4 ▶ $options //= {};
Condition50%1/2
$options //= {}
l!l
40
MC/DC0%0/1
$options //= {}
$options
Truth table50%1/2
A
A= $options
Aresult
11
00
188  
189 4 my @results;
190  
191 4 my $rel_info = $row->result_source->relationship_info($relation);
192 4 ▶ if ( $rel_info->{attrs}->{accessor} eq 'multi' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rel_info->{'attrs'}{'accessor'} eq 'multi') { } 1 3 4
193 1 my @rs = $row->$relation->all();
194 1 foreach my $rel_row (@rs) {
195 2 push @results, $self->_relation_with_attributes($rel_row, { %$options, relation => $relation, is_multi => 1, });
196 }
197 return {
198 1 data => \@results,
199 }
200 }
201 else {
202 return {
203 3 data => $self->_relation_with_attributes($row->$relation, { %$options, relation => $relation, })
204 }
205 }
206 }
207  
208 sub _relation_with_attributes {
209 5 ▶ my ($self, $row, $options) = @_;
Subroutine _relation_with_attributes: called CC=6 SCAR=18.4
210 5 ▶ my $with_kebab_case = $options->{kebab_case_attrs} // $self->kebab_case_attrs;
Condition66%2/3
$options->{"kebab_case_attrs"} // $self->kebab_case_attrs
l!l&&r!l&&!r
014
MC/DC50%1/2
$options->{"kebab_case_attrs"} // $self->kebab_case_attrs
$options->{"kebab_case_attrs"} $self->kebab_case_attrs
Truth table66%2/3
A // B
A= $options->{"kebab_case_attrs"}B= $self->kebab_case_attrs
ABresult
1X1
011
000
211 5 ▶ my $attrs_method = $options->{attributes_via} // $self->attributes_via;
Condition33%1/3
$options->{"attributes_via"} // $self->attributes_via
l!l&&r!l&&!r
050
MC/DC0%0/2
$options->{"attributes_via"} // $self->attributes_via
$options->{"attributes_via"} $self->attributes_via
Truth table33%1/3
A // B
A= $options->{"attributes_via"}B= $self->attributes_via
ABresult
1X1
011
000
212 5 my $type = $options->{relation};
213  
214 5 ▶ if ( !$options->{is_multi} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options->{"is_multi"}) 3 2 5
215 3 $type = Lingua::EN::Inflexion::noun( lc( $type ) )->plural;
216 }
217  
218 5 my %attributes = $row->$attrs_method();
219 5 ▶ if ($with_kebab_case) {
Branch: 1 branch
BranchTrueFalseTotal
if ($with_kebab_case) 1 4 5
220 1 %attributes = _kebab_case(%attributes);
221 1 $type =~ s/_/-/g;
222 }
223  
224 return {
225 5 ▶ id => delete $attributes{id} // $row->id,
Condition33%1/3
delete $attributes{"id"} // $row->id
l!l&&r!l&&!r
500
MC/DC0%0/2
delete $attributes{"id"} // $row->id
delete $attributes{"id"} $row->id
Truth table33%1/3
A // B
A= delete $attributes{"id"}B= $row->id
ABresult
1X1
011
000
226 type => $type,
227 attributes => \%attributes,
228 };
229 }
230  
231 sub _kebab_case {
232 5 ▶ my (%row) = @_;
Subroutine _kebab_case: called CC=2 SCAR=6.9
233 5 my %new_row;
234 5 foreach my $column ( keys(%row) ) {
235 10 my $value = $row{$column};
236 10 $column =~ s/_/-/g;
237 10 $new_row{$column} = $value;
238 }
239 5 return %new_row;
240 }
241  
242 4 1;
243  
244 __END__
245  
246 =encoding UTF-8
247  
248 =head1 NAME
249  
250 JSONAPI::Document - Turn DBIx results into JSON API documents.
251  
252 =head1 VERSION
253  
254 version 1.2
255  
256 =head1 SYNOPSIS
257  
258 use JSONAPI::Document;
259 use DBIx::Class::Schema;
260  
261 my $jsonapi = JSONAPI::Document->new({ api_url => 'http://example.com/api' });
262 my $schema = DBIx::Class::Schema->connect(['dbi:SQLite:dbname=:memory:', '', '']);
263 my $user = $schema->resultset('User')->find(1);
264  
265 # Builds a simple JSON API document, without any relationships
266 my $doc = $jsonapi->resource_document($user);
267  
268 # Same but with all relationships
269 my $doc = $jsonapi->resource_document($user, { with_relationships => 1 });
270  
271 # With only the author relationship
272 my $doc = $jsonapi->resource_document($user, { with_relationships => 1, relationships => ['author'] });
273  
274 # Fully blown resource document with all relationships and their attributes
275 my $doc = $jsonapi->compound_resource_document($user);
276  
277 # Multiple resource documents
278 my $docs = $jsonapi->resource_documents($schema->resultset('User'));
279  
280 =head1 DESCRIPTION
281  
282 Moo class that builds data structures according to the L<JSON API|http://jsonapi.org/format/> specification.
283  
284 =head1 NOTES
285  
286 JSON API documents require that you define the type of a document, which this
287 library does using the L<source_name|https://metacpan.org/pod/DBIx::Class::ResultSource#source_name>
288 of the result row. The type is also pluralised using L<Linua::EN::Inflexion|https://metacpan.org/pod/Lingua::EN::Inflexion>
289 while keeping relationship names intact (i.e. an 'author' relationship will still be called 'author', with the type 'authors').
290  
291 =head1 ATTRIBUTES
292  
293 =head2 data_dir
294  
295 Required; Directory string where this module can store computed document type strings. This should be
296 a directory that's ignored by your VCS.
297  
298 =head2 api_url
299  
300 Required; An absolute URL pointing to your servers JSON API namespace.
301  
302 =head2 kebab_case_attrs
303  
304 Boolean attribute; setting this will make the column keys for each document into
305 kebab-cased-strings instead of snake_cased. Default is false.
306  
307 =head2 attributes_via
308  
309 The method name to use throughout the creation of the resource document(s) to
310 get the attributes of the resources/relationships. This is useful if you
311 have a object that layers your DBIx results, you can instruct this
312 module to call that method instead of the default, which is
313 L<get_inflated_columns|https://metacpan.org/pod/DBIx::Class::Row#get_inflated_columns>.
314  
315 =head1 METHODS
316  
317 =head2 compound_resource_document(I<DBIx::Class::Row|Object> $row, I<HashRef> $options)
318  
319 A compound document is one that includes the resource object
320 along with the data of all its relationships.
321  
322 Returns a I<HashRef> with the following structure:
323  
324 {
325 data => {
326 id => 1,
327 type => 'authors',
328 attributes => {},
329 relationships => {},
330 },
331 included => [
332 {
333 id => 1,
334 type => 'posts',
335 attributes => { ... },
336 },
337 ...
338 ]
339 }
340  
341 The following options can be given:
342  
343 =over
344  
345 =item C<includes>
346  
347 An array reference specifying inclusion of a subset of relationships.
348 By default all the relationships will be included, use this if you
349 only want a subset of relationships (e.g. when accepting the C<includes>
350 query parameter in your application routes).
351  
352 =back
353  
354 =head2 resource_document(I<DBIx::Class::Row|Object> $row, I<HashRef> $options)
355  
356 Builds a single resource document for the given result row. Will optionally
357 include relationships that contain resource identifiers.
358  
359 Returns a I<HashRef> with the following structure:
360  
361 {
362 id => 1,
363 type => 'authors',
364 attributes => {},
365 relationships => {},
366 },
367  
368 View the resource document specification L<here|http://jsonapi.org/format/#document-resource-objects>.
369  
370 Uses L<Lingua::EN::Segment|metacpan.org/pod/Lingua::EN::Segment> to set the appropriate type of the
371 document. This is a bit expensive, but it ensures that your schema results source name gets hyphenated
372 appropriately when converted into its plural form. The resulting type is cached into the C<data_dir>
373 to minimize the need to re-compute the document type.
374  
375 The following options can be given:
376  
377 =over
378  
379 =item C<with_relationships> I<Bool>
380  
381 If true, will introspect the rows relationships and include each
382 of them in the relationships key of the document.
383  
384 =item C<with_attributes> I<Bool>
385  
386 If C<with_relationships> is true, for each resulting row of a relationship,
387 the attributes of that relation will be included.
388  
389 By default, each relationship will contain a L<links object|http://jsonapi.org/format/#document-links>.
390 If this option is true, links object will be replaced with attributes.
391  
392 =item C<includes> I<ArrayRef>
393  
394 If C<with_relationships> is true, this optional array ref can be
395 provided to include a subset of relations instead of all of them.
396  
397 =back
398  
399 =head2 resource_documents(I<DBIx::Class::Row|Object> $row, I<HashRef> $options)
400  
401 Builds the structure for multiple resource documents with a given resultset.
402  
403 Returns a I<HashRef> with the following structure:
404  
405 {
406 data => [
407 {
408 id => 1,
409 type => 'authors',
410 attributes => {},
411 relationships => {},
412 },
413 ...
414 ]
415 }
416  
417 See C<resource_document> for a list of options.
418  
419 =head1 LICENSE
420  
421 This code is released under the Perl 5 License.
422  
423 =cut
↑ Summary