Merge branch 'before-serializer'

This commit is contained in:
Yanick Champoux 2023-11-14 10:29:06 -05:00
commit 6ad18ac108
3 changed files with 20 additions and 5 deletions

View File

@ -7,7 +7,7 @@ vars:
TARGET_BRANCH: main TARGET_BRANCH: main
tasks: tasks:
format: pretty:
cmds: cmds:
- git diff-ls --diff-filter=ACMR {{.TARGET_BRANCH}} | grep -e '\.pm$\|\.t$' | xargs -IX perltidy -b X - git diff-ls --diff-filter=ACMR {{.TARGET_BRANCH}} | grep -e '\.pm$\|\.t$' | xargs -IX perltidy -b X

View File

@ -104,12 +104,18 @@ has attributes => (
} }
); );
has before_serialize => ( is => 'ro' );
sub serialize_data ( $self, $data, $extra_data = {}, $included = undef ) { sub serialize_data ( $self, $data, $extra_data = {}, $included = undef ) {
return [ map { $self->serialize_data( $_, $extra_data, $included ) } return [ map { $self->serialize_data( $_, $extra_data, $included ) }
@$data ] @$data ]
if ref $data eq 'ARRAY'; if ref $data eq 'ARRAY';
if ( $self->before_serialize ) {
$data = $self->before_serialize->( $data, $extra_data );
}
# it's a scalar? it's the id # it's a scalar? it's the id
return { id => $data, type => $self->type } unless ref $data; return { id => $data, type => $self->type } unless ref $data;

View File

@ -5,8 +5,7 @@ use Dancer2::Plugin::JsonApi::Registry;
use experimental qw/ signatures /; use experimental qw/ signatures /;
my $type = my $type = Dancer2::Plugin::JsonApi::Schema->new( 'type' => 'thing' );
Dancer2::Plugin::JsonApi::Schema->new( 'type' => 'thing' );
like $type->serialize( { attr1 => 'a', id => '123' }, { foo => 1 } ) => { like $type->serialize( { attr1 => 'a', id => '123' }, { foo => 1 } ) => {
jsonapi => { version => '1.0' }, jsonapi => { version => '1.0' },
@ -35,8 +34,7 @@ is( $serialized->{data}{id} => '12',
like $serialized->{data}, { links => { self => '/some/url' } }, "links"; like $serialized->{data}, { links => { self => '/some/url' } }, "links";
sub schema_serialize ( $schema, $data ) { sub schema_serialize ( $schema, $data ) {
return Dancer2::Plugin::JsonApi::Schema->new(%$schema) return Dancer2::Plugin::JsonApi::Schema->new(%$schema)->serialize($data);
->serialize($data);
} }
like( like(
@ -133,4 +131,15 @@ subtest 'attributes function' => sub {
is $serialized->{data}{attributes} => { 1 => 'id', b => 'a', d => 'c' }; 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(); done_testing();