-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathItemWritable.pm
More file actions
82 lines (61 loc) · 2.52 KB
/
ItemWritable.pm
File metadata and controls
82 lines (61 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package WebAPI::DBIC::Resource::HAL::Role::ItemWritable;
=head1 NAME
WebAPI::DBIC::Resource::HAL::Role::ItemWritable - methods handling HAL requests to update item resources
=cut
use Carp qw(croak confess);
use Devel::Dwarn;
use Moo::Role;
requires 'decode_json';
requires 'request';
around '_build_content_types_accepted' => sub {
my $orig = shift;
my $self = shift;
my $types = $self->$orig();
unshift @$types, { 'application/hal+json' => 'from_hal_json' };
return $types;
};
sub from_hal_json {
my $self = shift;
my $data = $self->decode_json( $self->request->content );
$self->update_resource($data, is_put_replace => 0);
return;
}
before '_do_update_resource' => sub {
my ($self, $item, $hal, $result_class) = @_;
my $links = delete $hal->{_links};
my $meta = delete $hal->{_meta};
my $embedded = delete $hal->{_embedded} || {};
for my $rel (keys %$embedded) {
my $rel_info = $result_class->relationship_info($rel)
or die "$result_class doesn't have a '$rel' relation\n";
die "$result_class _embedded $rel isn't a 'single' relationship\n"
if $rel_info->{attrs}{accessor} ne 'single';
my $rel_hal = $embedded->{$rel};
die "_embedded $rel data is not a hash\n"
if ref $rel_hal ne 'HASH';
# work out what keys to copy from the subitem we're about to update
# XXX this isn't required unless updating key fields - optimize
my %fk_map;
my $cond = $rel_info->{cond};
for my $sub_field (keys %$cond) {
my $our_field = $cond->{$sub_field};
$our_field =~ s/^self\.//x or confess "panic $rel $our_field";
$sub_field =~ s/^foreign\.//x or confess "panic $rel $sub_field";
$fk_map{$our_field} = $sub_field;
die "$result_class already contains a value for '$our_field'\n"
if defined $hal->{$our_field}; # null is ok
}
# update this subitem (and any resources embedded in it)
my $subitem = $item->$rel();
$subitem = $self->_do_update_resource($subitem, $rel_hal, $rel_info->{source});
# copy the keys of the subitem up to the item we're about to update
warn "$result_class $rel: propagating keys: @{[ %fk_map ]}\n"
if $ENV{WEBAPI_DBIC_DEBUG};
while ( my ($ourfield, $subfield) = each %fk_map) {
$hal->{$ourfield} = $subitem->$subfield();
}
# XXX perhaps save $subitem to optimise prefetch handling?
}
return;
};
1;