From 63ead8b937711b60c10c5c18f9c697d6a02f7541 Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Wed, 1 Nov 2023 16:03:28 -0400 Subject: [PATCH] add allowed_attributes --- lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm | 8 ++++++++ t/registry-schema.t | 11 +++++++++++ 2 files changed, 19 insertions(+) diff --git a/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm b/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm index 281cb0b..c919575 100644 --- a/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm +++ b/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm @@ -7,6 +7,8 @@ use Moo; use experimental qw/ signatures /; use List::AllUtils qw/ pairmap pairgrep /; +use Set::Object qw/set/; + =head1 ATTRIBUTES =head2 type @@ -38,6 +40,7 @@ has top_level_meta => (is => 'ro'); has relationships => (is => 'ro', default => sub { +{} }); has registry => ( is => 'ro' ); +has allowed_attributes => ( is => 'ro'); =head1 METHODS @@ -116,6 +119,11 @@ sub serialize_data ( $self, $data, $extra_data = {}, $included = undef ) { delete $s->{attributes} unless $s->{attributes}->%*; + if( $self->allowed_attributes ) { + delete $s->{attributes}{$_} for ( + set( keys $s->{attributes}->%* ) - set($self->allowed_attributes->@* ) )->@*; + } + return $s; } diff --git a/t/registry-schema.t b/t/registry-schema.t index a7036f7..8f773c8 100644 --- a/t/registry-schema.t +++ b/t/registry-schema.t @@ -77,5 +77,16 @@ subtest 'a single scalar == id', sub { }; }; +subtest 'allowed_attributes', sub { + my $serialized = Dancer2::Plugin::JsonApi::Registry::Schema->new( + type => 'thing', + allowed_attributes => ['foo'], + )->serialize( { id => 1, foo => 2, bar => 3 } ); + + is $serialized->{data} => { + type => 'thing', + id => 1, + attributes => { foo => 2, } }; +}; done_testing();