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
|
package MooseX::Net::API::Role::Serialization;
use 5.010;
use Try::Tiny;
use Moose::Role;
use MooseX::Net::API::Error;
has serializers => (
traits => ['Hash'],
is => 'rw',
isa => 'HashRef[MooseX::Net::API::Parser]',
default => sub { {} },
auto_deref => 1,
handles => {
_add_serializer => 'set',
_get_serializer => 'get',
},
);
sub get_content {
my ($self, $result) = @_;
my $content_type = $self->api_format // $result->header('Content-Type');
$content_type =~ s/(;.+)$//;
my $content;
if ($result->is_success && $result->code != 204) {
my @deserialize_order = ($content_type, $self->api_format);
$content = $self->deserialize($result->content, \@deserialize_order);
if (!$content) {
die MooseX::Net::API::Error->new(
reason => "can't deserialize content",
http_error => $result,
);
}
}
$content;
}
sub deserialize {
my ($self, $content, $list_of_formats) = @_;
foreach my $format (@$list_of_formats) {
my $s = $self->_get_serializer($format)
|| $self->_load_serializer($format);
next unless $s;
my $result = try { $s->decode($content) };
return $result if $result;
}
}
sub serialize {
my ($self, $content) = @_;
my $s = $self->_get_serializer($self->api_format);
my $result = try { $s->encode($content) };
return $result if $result;
}
sub _load_serializer {
my $self = shift;
my $format = shift || $self->api_format;
my $parser = "MooseX::Net::API::Parser::" . uc($format);
if (Class::MOP::load_class($parser)) {
my $o = $parser->new;
$self->_add_serializer($format => $o);
return $o;
}
}
1;
|