From 2e125c17715bfcf25863ee16f62ac7a927a412c8 Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Mon, 13 Nov 2023 13:12:48 -0500 Subject: [PATCH] misc Schema changes --- lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm | 15 +++++++++------ t/registry-schema.t | 2 +- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm b/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm index 1b505d3..f8d1e6a 100644 --- a/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm +++ b/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm @@ -115,7 +115,7 @@ sub serialize_data ( $self, $data, $extra_data = {}, $included = undef ) { my $s = { type => $self->type, - id => $self->gen_id($data) + id => $self->gen_id( $data, $extra_data ) }; if ( $self->links ) { @@ -134,12 +134,13 @@ sub serialize_data ( $self, $data, $extra_data = {}, $included = undef ) { my $t = $self->registry->serialize( $relationships{$key}{type}, $attr, \@inc ); - $s->{relationships}{$key}{data} = obj_ref( $t->{data}, \@inc ); + if ( my $data = obj_ref( $t->{data}, \@inc ) ) { + $s->{relationships}{$key}{data} = $data; + } if ( my $links = $relationships{$key}{links} ) { $s->{relationships}{$key}{links} = - gen_links( $links, $s->{relationships}{$key}{data}, - $extra_data ); + gen_links( $links, $data, $extra_data ); } push @$included, @inc if $included; @@ -163,15 +164,17 @@ sub obj_ref ( $data, $included ) { return $data if keys %$data == 2; + return unless keys %$data; + push @$included, $data; return +{ $data->%{qw/ id type/} }; } -sub gen_id ( $self, $data ) { +sub gen_id ( $self, $data, $xtra ) { my $id = $self->id; - return ref $id ? $id->($data) : $data->{$id}; + return ref $id ? $id->( $data, $xtra ) : $data->{$id}; } sub gen_links ( $links, $data, $extra_data = {} ) { diff --git a/t/registry-schema.t b/t/registry-schema.t index 6d2a8d1..ffe3a94 100644 --- a/t/registry-schema.t +++ b/t/registry-schema.t @@ -22,7 +22,7 @@ is( Dancer2::Plugin::JsonApi::Registry::Schema->new( my $serialized = schema_serialize( { 'type' => 'thing', - id => sub ($data) { $data->{x} . $data->{y} }, + id => sub ( $data, @ ) { $data->{x} . $data->{y} }, links => { self => '/some/url' }, }, { x => '1', y => '2' }