add before_serializer
This commit is contained in:
parent
a6303ca9f7
commit
38aba7d167
@ -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
|
||||
|
||||
|
@ -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;
|
||||
|
||||
|
17
t/schema.t
17
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();
|
||||
|
Loading…
Reference in New Issue
Block a user