auto-add the self link within the app

releases
Yanick Champoux 2023-11-13 10:38:51 -05:00
parent ebbb5f9466
commit 0a2eee55ce
3 changed files with 33 additions and 0 deletions

View File

@ -30,6 +30,8 @@ has types => (
default => sub { +{} },
);
has app => ( is => 'ro', );
=head2 add_type($type, $definition = {})
Adds a data type to the registry.

View File

@ -66,6 +66,11 @@ sub serialize ( $self, $data, $extra_data = {} ) {
$serial->{links} = gen_links( $self->top_level_links, $data, $extra_data )
if $self->top_level_links;
if ( $self->registry and $self->registry->app ) {
$serial->{links}{self} = $self->registry->app->request->path;
}
$serial->{meta} = gen_links( $self->top_level_meta, $data, $extra_data )
if $self->top_level_meta;

View File

@ -1,6 +1,7 @@
use Test2::V0;
use Dancer2::Plugin::JsonApi::Registry::Schema;
use Dancer2::Plugin::JsonApi::Registry;
use experimental qw/ signatures /;
@ -96,4 +97,29 @@ subtest 'empty data', sub {
ok( !$serialized->{data}, "there is no data" );
};
package FakeRequest {
use Moo;
has path => ( is => 'ro', default => '/some/path' );
}
package FakeApp {
use Moo;
has request => (
is => 'ro',
default => sub {
FakeRequest->new;
}
);
}
subtest "add the self link if tied to the app" => sub {
my $serialized = Dancer2::Plugin::JsonApi::Registry::Schema->new(
type => 'thing',
registry =>
Dancer2::Plugin::JsonApi::Registry->new( app => FakeApp->new )
)->serialize(undef);
is $serialized->{links}{self} => '/some/path';
};
done_testing();