From e93942cb61b8f44e93347fdd2a49df8e72e72afa Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Mon, 13 Nov 2023 12:29:37 -0500 Subject: [PATCH] attributes can be a function --- lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm | 18 ++++++++++++++++-- t/registry-schema.t | 13 ++++++++++++- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm b/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm index b500f82..1b505d3 100644 --- a/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm +++ b/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm @@ -90,6 +90,20 @@ Serializes the inner C<$data>. =cut +has attributes => ( + is => 'ro', + default => sub { + my $self = shift; + return sub { + my ( $data, $extra_data ) = @_; + return {} if ref $data ne 'HASH'; + my @keys = grep { not $self->relationships->{$_} } + grep { $_ ne $self->id } keys %$data; + return { $data->%{@keys} }; + } + } +); + sub serialize_data ( $self, $data, $extra_data = {}, $included = undef ) { return [ map { $self->serialize_data( $_, $extra_data, $included ) } @@ -108,12 +122,12 @@ sub serialize_data ( $self, $data, $extra_data = {}, $included = undef ) { $s->{links} = gen_links( $self->links, $data, $extra_data ); } - $s->{attributes} = +{ pairgrep { $a ne $self->id } %$data }; + $s->{attributes} = gen_links( $self->attributes, $data, $extra_data ); my %relationships = $self->relationships->%*; for my $key ( keys %relationships ) { - my $attr = delete $s->{attributes}{$key} or next; + my $attr = $data->{$key}; my @inc; diff --git a/t/registry-schema.t b/t/registry-schema.t index 45da861..6d2a8d1 100644 --- a/t/registry-schema.t +++ b/t/registry-schema.t @@ -120,6 +120,17 @@ subtest "add the self link if tied to the app" => sub { )->serialize(undef); is $serialized->{links}{self} => '/some/path'; - }; + +subtest 'attributes function' => sub { + my $serialized = Dancer2::Plugin::JsonApi::Registry::Schema->new( + type => 'thing', + attributes => sub ( $data, @ ) { + return +{ reverse %$data },; + }, + )->serialize( { id => 1, 'a' .. 'd' } ); + + is $serialized->{data}{attributes} => { 1 => 'id', b => 'a', d => 'c' }; +}; + done_testing();