| 1 | package Mojolicious::Plugin::Fondation::Schema::Result::Base; | ||
| 2 | $Mojolicious::Plugin::Fondation::Schema::Result::Base::VERSION = '0.08'; | ||
| 3 | # ABSTRACT: Base class for all Fondation DBIx::Class Result classes | ||
| 4 | |||
| 5 | use strict; | ||
| 6 | use warnings; | ||
| 7 | use base 'DBIx::Class::Core'; | ||
| 8 | use Scalar::Util qw(blessed); | ||
| 9 | |||
| 10 | # ── TO_JSON — generic serialization with relationships ── | ||
| 11 | |||
| 12 | sub TO_JSON { | ||
| 13 | my $self = shift; | ||
| 14 | my %data = $self->get_columns; | ||
| 15 | |||
| 16 | for my $rel ($self->result_source->relationships) { | ||
| 17 | next unless $self->has_column_loaded($rel) | ||
| 18 | || exists $self->{_relationship_data}{$rel}; | ||
| 19 | # Access prefetched data directly (async relationships return Futures or hashrefs) | ||
| 20 | my $obj = exists $self->{_relationship_data}{$rel} | ||
| 21 | ? $self->{_relationship_data}{$rel} | ||
| 22 | : eval { $self->$rel }; | ||
| 23 | next if !$obj || (blessed($obj) && $obj->isa('Future')); | ||
| 24 | |||
| 25 | if (ref $obj eq 'ARRAY') { | ||
| 26 | $data{$rel} = [ map { blessed($_) ? $_->TO_JSON : $_ } @$obj ]; | ||
| 27 | } | ||
| 28 | elsif (blessed $obj) { | ||
| 29 | $data{$rel} = $obj->TO_JSON; | ||
| 30 | } | ||
| 31 | else { | ||
| 32 | $data{$rel} = $obj; # unblessed hashref (prefetched async) | ||
| 33 | } | ||
| 34 | } | ||
| 35 | |||
| 36 | # ── many_to_many_async relationships ── | ||
| 37 | # Discovered via _many_to_many metadata (populated by | ||
| 38 | # DBIx::Class::Relationship::ManyToMany::Async). | ||
| 39 | # When data was prefetched (e.g. $rs->with('groups')), | ||
| 40 | # the accessor returns Future->done(\@targets) — we | ||
| 41 | # extract synchronously via is_done + get. | ||
| 42 | # Without prefetch, the Future is not done → silently skipped. | ||
| 43 | { | ||
| 44 | no strict 'refs'; | ||
| 45 | my $m2m = ${ ref($self) . '::_many_to_many' } // {}; | ||
| 46 | for my $meth (keys %$m2m) { | ||
| 47 | next unless $self->can($meth); | ||
| 48 | my $future = $self->$meth; | ||
| 49 | next unless $future->is_done; | ||
| 50 | my $targets = $future->get; | ||
| 51 | $data{$meth} | ||
| 52 | = [ map { blessed($_) ? $_->TO_JSON : $_ } @$targets ] | ||
| 53 | if $targets && @$targets; | ||
| 54 | } | ||
| 55 | } | ||
| 56 | |||
| 57 | # Serialize DateTime columns to ISO 8601 strings | ||
| 58 | for my $key (keys %data) { | ||
| 59 | my $val = $data{$key}; | ||
| 60 | $data{$key} = $val->iso8601 if blessed($val) && $val->isa('DateTime'); | ||
| 61 | } | ||
| 62 | |||
| 63 | return \%data; | ||
| 64 | } | ||
| 65 | |||
| 66 | 1; | ||
| 67 | |||
| 68 | __END__ |