use 5.38.0; =head1 DESCRIPTION Serializer for JSON:API. Takes in a data structure, munge it to conforms to the JSON:API format (potentially based on a provided registry of JSON:API schemas), and encode it as JSON. Note that using Dancer2::Plugin::JsonApi in an app will automatically set C as its serializer if it's not already defined. =head1 SYNOPSIS As part of a Dancer2 App: # in config.yaml serializer: JsonApi As a standalone module: use Dancer2::Serializer::JsonApi; use Dancer2::Plugin::JsonApi::Registry; my $registry = Dancer2::Plugin::JsonApi::Registry->new; $registry->add_type( 'spaceship' => { relationships => { crew => { type => 'person' } } } ); $registry->add_type( 'person' ); my $serializer = Dancer2::Serializer::JsonApi->new( registry => $registry ); my $serialized = $serializer->serialize([ 'spaceship', { id => 1, name => 'Unrequited Retribution', crew => [ { id => 2, name => 'One-eye Flanagan', species => 'human' }, { id => 3, name => 'Flabgor', species => 'Moisterian' }, ] } ]); =cut package Dancer2::Serializer::JsonApi; use Dancer2::Plugin::JsonApi::Registry; use Dancer2::Serializer::JSON; use Moo; =head1 ATTRIBUTES =head2 content_type Returns the content type used by the serializer, which is C; =cut has content_type => ( is => 'ro', default => 'application/vnd.api+json' ); with 'Dancer2::Core::Role::Serializer'; =head2 registry The L to use. =cut has registry => ( is => 'rw', default => sub { Dancer2::Plugin::JsonApi::Registry->new } ); =head2 json_serializer The underlying JSON serializer. Defaults to L. =cut has json_serializer => ( is => 'ro', default => sub { Dancer2::Serializer::JSON->new } ); =head1 METHODS =head2 $self->serialize( [ $type, $data, $xtra ]) Serializes the C<$data> using the C<$type> from the registry. The returned value will be a JSON string. =cut sub serialize { my ( $self, $data ) = @_; return $self->json_serializer->serialize( $self->registry->serialize(@$data) ); } =head2 $self->deserialize( $json_string ) Takes in the serialized C<$json_string> and recreate data out of it. UNIMPLENTED =cut sub deserialize { ... } 1;