From 0a2eee55ce5cd7c91e35cb91c8d206595fa58cd1 Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Mon, 13 Nov 2023 10:38:51 -0500 Subject: [PATCH] auto-add the self link within the app --- lib/Dancer2/Plugin/JsonApi/Registry.pm | 2 ++ lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm | 5 ++++ t/registry-schema.t | 26 +++++++++++++++++++ 3 files changed, 33 insertions(+) diff --git a/lib/Dancer2/Plugin/JsonApi/Registry.pm b/lib/Dancer2/Plugin/JsonApi/Registry.pm index 9b9e9ac..4d6f2c2 100644 --- a/lib/Dancer2/Plugin/JsonApi/Registry.pm +++ b/lib/Dancer2/Plugin/JsonApi/Registry.pm @@ -30,6 +30,8 @@ has types => ( default => sub { +{} }, ); +has app => ( is => 'ro', ); + =head2 add_type($type, $definition = {}) Adds a data type to the registry. diff --git a/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm b/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm index 9ec8ea4..b500f82 100644 --- a/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm +++ b/lib/Dancer2/Plugin/JsonApi/Registry/Schema.pm @@ -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; diff --git a/t/registry-schema.t b/t/registry-schema.t index 9b8ead0..45da861 100644 --- a/t/registry-schema.t +++ b/t/registry-schema.t @@ -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();