diff --git a/Taskfile.yaml b/Taskfile.yaml index 83f77eb..257d731 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -7,7 +7,7 @@ vars: TARGET_BRANCH: main tasks: - format: + pretty: cmds: - git diff-ls --diff-filter=ACMR {{.TARGET_BRANCH}} | grep -e '\.pm$\|\.t$' | xargs -IX perltidy -b X diff --git a/lib/Dancer2/Plugin/JsonApi/Schema.pm b/lib/Dancer2/Plugin/JsonApi/Schema.pm index adf9fc6..1ae6c40 100644 --- a/lib/Dancer2/Plugin/JsonApi/Schema.pm +++ b/lib/Dancer2/Plugin/JsonApi/Schema.pm @@ -104,12 +104,18 @@ has attributes => ( } ); +has before_serialize => ( is => 'ro' ); + sub serialize_data ( $self, $data, $extra_data = {}, $included = undef ) { return [ map { $self->serialize_data( $_, $extra_data, $included ) } @$data ] if ref $data eq 'ARRAY'; + if ( $self->before_serialize ) { + $data = $self->before_serialize->( $data, $extra_data ); + } + # it's a scalar? it's the id return { id => $data, type => $self->type } unless ref $data; diff --git a/t/schema.t b/t/schema.t index 5a2495c..1c5147b 100644 --- a/t/schema.t +++ b/t/schema.t @@ -5,8 +5,7 @@ use Dancer2::Plugin::JsonApi::Registry; use experimental qw/ signatures /; -my $type = - Dancer2::Plugin::JsonApi::Schema->new( 'type' => 'thing' ); +my $type = Dancer2::Plugin::JsonApi::Schema->new( 'type' => 'thing' ); like $type->serialize( { attr1 => 'a', id => '123' }, { foo => 1 } ) => { jsonapi => { version => '1.0' }, @@ -35,8 +34,7 @@ is( $serialized->{data}{id} => '12', like $serialized->{data}, { links => { self => '/some/url' } }, "links"; sub schema_serialize ( $schema, $data ) { - return Dancer2::Plugin::JsonApi::Schema->new(%$schema) - ->serialize($data); + return Dancer2::Plugin::JsonApi::Schema->new(%$schema)->serialize($data); } like( @@ -133,4 +131,15 @@ subtest 'attributes function' => sub { is $serialized->{data}{attributes} => { 1 => 'id', b => 'a', d => 'c' }; }; +subtest 'before_serializer' => sub { + my $serialized = Dancer2::Plugin::JsonApi::Schema->new( + type => 'thing', + before_serialize => sub ( $data, @ ) { + return +{ %$data, nbr_attrs => scalar keys %$data }; + }, + )->serialize( { id => 1, a => 'b' } ); + + is $serialized->{data}{attributes}{nbr_attrs} => 2; +}; + done_testing();