File: Serializer.pm

package info (click to toggle)
librole-rest-client-perl 0.23-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster, forky, sid, trixie
  • size: 180 kB
  • sloc: perl: 327; makefile: 4
file content (114 lines) | stat: -rw-r--r-- 2,135 bytes parent folder | download
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package Role::REST::Client::Serializer;
$Role::REST::Client::Serializer::VERSION = '0.23';
use Try::Tiny;
use Moo;
use Types::Standard qw(Enum InstanceOf);
use Data::Serializer::Raw;

has 'type' => (
	isa => Enum[qw{application/json application/xml application/yaml application/x-www-form-urlencoded text/javascript}],
	is  => 'rw',
	default => sub { 'application/json' },
);

has 'serializer' => (
	isa => InstanceOf['Data::Serializer::Raw'],
	is => 'ro',
	default => \&_set_serializer,
	lazy => 1,
);

our %modules = (
	'application/json' => {
		module => 'JSON',
	},
	'application/xml' => {
		module => 'XML::Simple',
	},
	'application/yaml' => {
		module => 'YAML',
	},
	'application/x-www-form-urlencoded' => {
		module => 'FORM',
	},
	'text/javascript' => {
	        module => 'JSON',	
	},
);

sub _set_serializer {
	my $self = shift;
	return unless $modules{$self->type};

	my $module = $modules{$self->type}{module};
	return $module if $module eq 'FORM';

	return Data::Serializer::Raw->new(
		serializer => $module,
	);
}

sub content_type {
	my ($self) = @_;
	return $self->type;
}

sub serialize {
	my ($self, $data) = @_;
	return unless $self->serializer;

	my $result;
	try {
		$result = $self->serializer->serialize($data)
	} catch {
		warn "Couldn't serialize data with " . $self->type . ": $_";
	};

	return $result;
}

sub deserialize {
	my ($self, $data) = @_;
	return unless $self->serializer;

	my $result;
	try {
		$result = $self->serializer->deserialize($data);
	} catch {
        use Data::Dumper 'Dumper';
        $Data::Dumper::Maxdepth = 4;
        warn 'Data was ' . Dumper([ $data ]), ' ';
		warn "Couldn't deserialize data with " . $self->type . ": $_";
	};

	return $result;
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Role::REST::Client::Serializer - Serialization class for REST

=head1 VERSION

version 0.23

=head1 AUTHOR

Kaare Rasmussen <kaare at cpan dot org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2018 by Kaare Rasmussen.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut