add the serializer

This commit is contained in:
Yanick Champoux 2023-11-10 15:30:25 -05:00
parent 936b2344cd
commit 52eba22e47
3 changed files with 63 additions and 7 deletions

View File

@ -21,8 +21,8 @@ Returns the serialized form of C<$data>.
=cut =cut
sub serialize($self,$type,$data,$extra_data={}) { sub serialize ( $self, $type, $data, $extra_data = {} ) {
return $self->type($type)->serialize($data,$extra_data); return $self->type($type)->serialize( $data, $extra_data );
} }
has types => ( has types => (
@ -36,7 +36,7 @@ Adds a data type to the registry.
=cut =cut
sub add_type($self,$type,$definition={}) { sub add_type ( $self, $type, $definition = {} ) {
$self->{types}{$type} = Dancer2::Plugin::JsonApi::Registry::Schema->new( $self->{types}{$type} = Dancer2::Plugin::JsonApi::Registry::Schema->new(
registry => $self, registry => $self,
type => $type, type => $type,
@ -51,8 +51,9 @@ error if the type does not exist.
=cut =cut
sub type($self,$type) { sub type ( $self, $type ) {
return $self->types->{$type} || croak "type '$type' not found"; return $self->types->{$type} //=
Dancer2::Plugin::JsonApi::Registry::Schema->new( type => $type );
} }
1; 1;

View File

@ -0,0 +1,33 @@
use 5.38.0;
package Dancer2::Serializer::JsonApi;
use Dancer2::Plugin::JsonApi::Registry;
use Dancer2::Serializer::JSON;
use Moo;
has content_type => ( is => 'ro', default => 'application/vnd.api+json' );
with 'Dancer2::Core::Role::Serializer';
has registry => (
is => 'rw',
default => sub { Dancer2::Plugin::JsonApi::Registry->new }
);
has json_serializer => (
is => 'ro',
default => sub { Dancer2::Serializer::JSON->new }
);
sub serialize {
my ( $self, $data ) = @_;
return $self->json_serializer->serialize(
$self->registry->serialize(%$data) );
}
sub deserialize { ... }
1;

22
t/serializer.t Normal file
View File

@ -0,0 +1,22 @@
use Test2::V0;
use JSON qw/ from_json /;
use Dancer2::Serializer::JsonApi;
my $serializer =
Dancer2::Serializer::JsonApi->new( log_cb => sub { warn @_ } );
my $data = { 'thing' =>, { id => 2 } };
my $serialized = $serializer->serialize($data);
like from_json($serialized),
{ jsonapi => { version => '1.0' },
data => { id => 2, type => 'thing' },
};
todo 'not implemented yet' => sub {
is $serializer->deserialize($serialized) => $data;
};
done_testing;