Debian Codegraph @

lib/Dancer2/Serializer/Mutable.pm

raw
1 package Dancer2::Serializer::Mutable;
2 # ABSTRACT: Serialize and deserialize content based on HTTP header
3 $Dancer2::Serializer::Mutable::VERSION = '2.2.2';
4 use Moo;
5 use Carp 'croak';
6 use Encode;
7 use Module::Runtime 'require_module';
8 with 'Dancer2::Core::Role::Serializer';
9
10 use constant DEFAULT_CONTENT_TYPE => 'application/json';
11
12 has '+content_type' => ( default => DEFAULT_CONTENT_TYPE() );
13
14 my $serializer = {
15 'YAML' => {
16 to => sub { Dancer2::Core::DSL::to_yaml(@_) },
17 from => sub { Dancer2::Core::DSL::from_yaml(@_) },
18 },
19 'JSON' => {
20 to => sub { Dancer2::Core::DSL::to_json(@_) },
21 from => sub { Dancer2::Core::DSL::from_json(@_) },
22 },
23 };
24
25 has enable_dumper => (
26 is => 'ro',
27 lazy => 1,
28 default => sub { $_[0]->config->{enable_dumper} || 0 },
29 );
30
31 has mapping => (
32 is => 'ro',
33 lazy => 1,
34 default => sub {
35 my $self = shift;
36
37 if ( my $mapping = $self->config->{mapping} ) {
38
39 # initialize non-default serializers
40 for my $s ( values %$mapping ) {
41 # TODO allow for arguments via the config
42 next if $serializer->{$s};
43
44 if ( $s eq 'Dumper' && !$self->enable_dumper ) {
45 croak
46 "The Dumper serializer is disabled. Set "
47 . "engines.serializer.Mutable.enable_dumper to a "
48 . "true value to use it. This requires the "
49 . "Dancer2::Serializer::Dumper distribution to be "
50 . "installed.";
51 }
52
53 $self->_load_serializer($s);
54 }
55
56 return $mapping;
57 }
58
59 my %default_mapping = (
60 'text/x-yaml' => 'YAML',
61 'text/html' => 'YAML',
62 'text/x-json' => 'JSON',
63 'application/json' => 'JSON',
64 );
65
66 if ( $self->enable_dumper ) {
67 $default_mapping{'text/x-data-dumper'} = 'Dumper';
68 $self->_load_serializer('Dumper');
69 }
70
71 return \%default_mapping;
72 },
73 );
74
75 sub _load_serializer {
76 my ( $self, $name ) = @_;
77
78 return $serializer->{$name} if $serializer->{$name};
79
80 my $serializer_class = "Dancer2::Serializer::$name";
81 require_module($serializer_class);
82 my $serializer_object = $serializer_class->new;
83 return $serializer->{$name} = {
84 from => sub { shift; $serializer_object->deserialize(@_) },
85 to => sub { shift; $serializer_object->serialize(@_) },
86 };
87 }
88
89 sub serialize {
90 my ( $self, $entity ) = @_;
91
92 # Look for valid format in the headers
93 my $format = $self->_get_content_type('accept');
94
95 # Match format with a serializer and return
96 $format and return $serializer->{$format}{'to'}->(
97 $self, $entity
98 );
99
100 # If none is found then just return the entity without change
101 return $entity;
102 }
103
104 sub deserialize {
105 my ( $self, $content ) = @_;
106
107 my $format = $self->_get_content_type('content_type');
108 $format and return $serializer->{$format}{'from'}->($self, $content);
109
110 return $content;
111 }
112
113 sub _get_content_type {
114 my ($self, $header) = @_;
115
116 if ( $self->has_request ) {
117 # Search for the first HTTP header variable which specifies
118 # supported content. Both content_type and accept are checked
119 # for backwards compatibility.
120 foreach my $method ( $header, qw<content_type accept> ) {
121 if ( my $value = $self->request->header($method) ) {
122 # A header value may carry parameters after the content
123 # type itself (e.g. 'text/x-yaml; charset=utf-8'). Strip
124 # anything from the first ';' onward, trim surrounding
125 # whitespace and lowercase what's left, so the lookup
126 # matches on the content type alone - the mapping's keys
127 # are bare lowercase content types. (An Accept header
128 # listing several comma-separated types is not split
129 # further here: the whole remainder is matched as one
130 # string, so only a single-type Accept is recognised.)
131 ( my $type = $value ) =~ s/;.*$//;
132 $type =~ s/^\s+|\s+$//g;
133 $type = lc $type;
134 if ( my $serializer = $self->mapping->{$type} ) {
135 $self->set_content_type($type);
136 return $serializer;
137 }
138 }
139 }
140 }
141
142 # If none if found, return the default, 'JSON'.
143 $self->set_content_type( DEFAULT_CONTENT_TYPE() );
144 return 'JSON';
145 }
146
147 1;
148
149 __END__
150
151 =pod
152
153 =encoding UTF-8
154
155 =head1 NAME
156
157 Dancer2::Serializer::Mutable - Serialize and deserialize content based on HTTP header
158
159 =head1 VERSION
160
161 version 2.2.2
162
163 =head1 SYNOPSIS
164
165 # in config.yml
166 serializer: Mutable
167
168 engines:
169 serializer:
170 Mutable:
171 mapping:
172 'text/x-yaml' : YAML
173 'text/html' : YAML
174 'text/x-json' : JSON
175 'application/json' : JSON
176
177 # in the app
178 put '/something' => sub {
179 # deserialized from request
180 my $name = param( 'name' );
181
182 ...
183
184 # will be serialized to the most
185 # fitting format
186 return { message => "user $name added" };
187 };
188
189 =head1 DESCRIPTION
190
191 This serializer will try find the best (de)serializer for a given request.
192 For this, it will pick the first valid content type found from a list, and
193 use its related serializer. The list, and its order, is not the same in both
194 directions:
195
196 =over
197
198 =item
199
200 When B<deserializing> an incoming request body (that is, working out how to
201 read it), the order is: the B<content_type> from the request headers, then
202 the B<accept> from the request headers, then the default of
203 B<application/json>.
204
205 =item
206
207 When B<serializing> a response (that is, working out what to send back), the
208 order is: the B<accept> from the request headers, then the B<content_type>
209 from the request headers, then the default of B<application/json>. Consulting
210 C<Accept> first is deliberate - it is the header a client uses to say what it
211 wants back, which need not match the content type of what it sent.
212
213 =back
214
215 In both directions, a header's value is matched against the mapping on its
216 content type alone: any C<;>-separated parameters (such as
217 C<; charset=utf-8>) are stripped, surrounding whitespace is trimmed, and the
218 result is lowercased before comparison. So C<Content-Type: text/x-yaml>,
219 C<Content-Type: text/x-yaml; charset=utf-8> and C<Content-Type: TEXT/X-YAML>
220 are all recognised as C<text/x-yaml>. An C<Accept> header listing several
221 comma-separated types is not split further - it is matched as a whole after
222 parameter-stripping, so only a single-type C<Accept> value is recognised;
223 anything else falls through to the next header or the default.
224
225 The content-type/serializer mapping that C<Dancer2::Serializer::Mutable>
226 uses is
227
228 serializer | content types
229 ----------------------------------------------------------
230 Dancer2::Serializer::YAML | text/x-yaml, text/html
231 Dancer2::Serializer::JSON | text/x-json, application/json
232
233 The keys above are bare, lowercase content types - not raw header values - as
234 described above.
235
236 A different mapping can be provided via the config file. For example,
237 the default mapping would be configured as
238
239 engines:
240 serializer:
241 Mutable:
242 mapping:
243 'text/x-yaml' : YAML
244 'text/html' : YAML
245 'text/x-json' : JSON
246 'application/json' : JSON
247
248 The values are the serializers to use. Serialization for C<YAML> and C<JSON>
249 are done using internal Dancer mechanisms. Any other serializer will be taken
250 to be a Dancer2 serialization class (minus the C<Dancer2::Serializer::>
251 prefix) and an instance of it will be used to serialize/deserialize data.
252 For example, adding L<Dancer2::Serializer::XML> to the mapping would be:
253
254 engines:
255 serializer:
256 Mutable:
257 mapping:
258 'text/x-yaml' : YAML
259 'text/html' : YAML
260 'text/x-json' : JSON
261 'text/xml' : XML
262
263 =head2 Dumper
264
265 The Dumper serializer is B<not> available by default, as it deserializes
266 request content by evaluating it as Perl code, which is insecure and a bad
267 idea. If you really want to use it, you must explicitly opt in, and you must
268 have the C<Dancer2-Serializer-Dumper> distribution installed. You can then
269 enable it either by adding it to your mapping and setting
270 C<enable_dumper>:
271
272 engines:
273 serializer:
274 Mutable:
275 enable_dumper: 1
276 mapping:
277 'text/x-yaml' : YAML
278 'text/html' : YAML
279 'text/x-data-dumper' : Dumper
280 'text/x-json' : JSON
281 'application/json' : JSON
282
283 or by using the default mapping with C<enable_dumper> set, which adds
284 C<text/x-data-dumper> to the default mapping:
285
286 engines:
287 serializer:
288 Mutable:
289 enable_dumper: 1
290
291 Attempting to use the Dumper serializer without setting C<enable_dumper>
292 to a true value will cause a fatal error.
293
294 =head2 INTERNAL METHODS
295
296 The following methods are used internally by C<Dancer2> and are not made
297 accessible via the DSL.
298
299 =head2 serialize
300
301 Serialize a data structure. The format it is serialized to is determined
302 automatically as described above. It can be one of YAML, JSON, defaulting
303 to JSON if there's no clear preference from the request.
304
305 =head2 deserialize
306
307 Deserialize the provided serialized data to a data structure. The type of
308 serialization format depends on the request's content-type. For now, it can
309 be one of YAML, JSON.
310
311 =head2 content_type
312
313 Returns the content-type that was used during the last C<serialize> /
314 C<deserialize> call. B<WARNING> : you must call C<serialize> / C<deserialize>
315 before calling C<content_type>. Otherwise the return value will be C<undef>.
316
317 =head1 AUTHOR
318
319 Dancer Core Developers
320
321 =head1 COPYRIGHT AND LICENSE
322
323 This software is copyright (c) 2026 by Alexis Sukrieh.
324
325 This is free software; you can redistribute it and/or modify it under
326 the same terms as the Perl 5 programming language system itself.
327
328 =cut