summary refs log tree commit diff
path: root/lib/MooseX/Net/API/Role/Serialization.pm
blob: 1a090d1dbb5f4cdebc896d6722fc778a0e52fc2b (plain) (blame)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package MooseX::Net::API::Role::Serialization;

# ABSTRACT: do (de)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;

=head1 SYNOPSIS

=head1 DESCRIPTION

=head2 ATTRIBUTES

=over 4

=item B<serializers>

=back

=head2 METHODS

=over 4

=item B<get_content>

=item B<serialize>

=item B<deserialize>

=back