blib/lib/Dancer2/Plugin/Swagger2.pm

filter: Statementstmt 86.6% 13 / 15 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 90.0% 18 / 20 CC 1 SCAR 0.6
CC
1
Cov
87%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 package Dancer2::Plugin::Swagger2;
2  
3 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 # ABSTRACT: A Dancer2 plugin for creating routes from a Swagger2 spec
7 our $VERSION = '0.003_002'; # TRIAL VERSION
8  
9 4 ▶use Dancer2::Plugin;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 4 ▶use Module::Runtime 'use_module';
Subroutine BEGIN: called CC=1 SCAR=0.0
11 0 ▶use Swagger2;
Subroutine BEGIN: called CC=1 SCAR=2.6
12 use Swagger2::SchemaValidator;
13  
14  
15 sub DEBUG { !!$ENV{SWAGGER2_DEBUG} }
16  
17  
18 register swagger2 => sub {
19 my ( $dsl, %args ) = @_;
20 my $conf = plugin_setting;
21  
22 ### get arguments/config values/defaults ###
23  
24 my $controller_factory =
25 $args{controller_factory} || \&_default_controller_factory;
26 my $url = $args{url} or die "argument 'url' missing";
27 my $create_options_route =
28 exists $args{create_options_route} ? !!$args{create_options_route}
29 : exists $conf->{create_options_route} ? !!$conf->{create_options_route}
30 : '';
31 my $validate_spec =
32 exists $args{validate_spec} ? !!$args{validate_spec}
33 : exists $conf->{validate_spec} ? !!$conf->{validate_spec}
34 : 1;
35 my $validate_requests =
36 exists $args{validate_requests} ? !!$args{validate_requests}
37 : exists $conf->{validate_requests} ? !!$conf->{validate_requests}
38 : $validate_spec;
39 my $validate_responses =
40 exists $args{validate_responses} ? !!$args{validate_responses}
41 : exists $conf->{validate_responses} ? !!$conf->{validate_responses}
42 : $validate_spec;
43  
44 # parse Swagger2 file
45 my $spec = Swagger2->new($url)->expand;
46  
47 if ( $validate_spec or $validate_requests or $validate_responses ) {
48 if ( my @errors = $spec->validate ) {
49 if ($validate_spec) {
50 die join "\n" => "Swagger2: Invalid spec:", @errors;
51 }
52 else {
53 warn "Spec contains errors but"
54 . " request/response validation is enabled!";
55 }
56 }
57 }
58  
59 my $basePath = $spec->api_spec->get('/basePath');
60 my $paths = $spec->api_spec->get('/paths'); # TODO might be undef?
61  
62 while ( my ( $path => $path_spec ) = each %$paths ) {
63 my $dancer2_path = $path;
64  
65 $basePath and $dancer2_path = $basePath . $dancer2_path;
66  
67 # adapt Swagger2 syntax for URL path arguments to Dancer2 syntax
68 # '/path/{argument}' -> '/path/:argument'
69 $dancer2_path =~ s/\{([^{}]+?)\}/:$1/g;
70  
71 my @http_methods = sort keys %$path_spec;
72  
73 if ($create_options_route) {
74 my $allow_methods = join ', ' => 'OPTIONS', map uc, @http_methods;
75 $dsl->options(
76 $dancer2_path => sub {
77 $dsl->headers(
78 Allow => $allow_methods, # RFC 2616 HTTP/1.1
79 'Access-Control-Allow-Methods' => $allow_methods, # CORS
80 'Access-Control-Max-Age' => 60 * 60 * 24,
81 );
82 },
83 );
84 }
85  
86 for my $http_method (@http_methods) {
87 my $method_spec = $path_spec->{ $http_method };
88 my $coderef = $controller_factory->(
89 $method_spec, $http_method, $path, $dsl, $conf, \%args
90 ) or next;
91  
92 DEBUG and warn "Add route $http_method $dancer2_path";
93  
94 my $params = $method_spec->{parameters};
95  
96 # Dancer2 DSL keyword is different from HTTP method
97 $http_method eq 'delete' and $http_method = 'del';
98  
99 $dsl->$http_method(
100 $dancer2_path => sub {
101 my @args = @_;
102  
103 if ($validate_requests) {
104 my @errors =
105 _validate_request( $method_spec, $dsl->app->request );
106  
107 if (@errors) {
108 DEBUG and warn "Invalid request: @errors\n";
109 $dsl->status(400);
110 return { errors => [ map { "$_" } @errors ] };
111 }
112 }
113  
114 my $result = $coderef->(@args);
115  
116 if ($validate_responses) {
117 my @errors =
118 _validate_response( $method_spec, $dsl->response,
119 $result );
120  
121 if (@errors) {
122 DEBUG and warn "Invalid response: @errors\n";
123 $dsl->status(500);
124  
125 # TODO hide details of server-side errors?
126 return { errors => [ map { "$_" } @errors ] };
127 }
128 }
129  
130 return $result;
131 }
132 );
133 }
134 }
135 };
136  
137 register_plugin;
138  
139 sub _validate_request {
140 my ( $method_spec, $request ) = @_;
141  
142 my @errors;
143  
144 for my $parameter_spec ( @{ $method_spec->{parameters} } ) {
145 my $in = $parameter_spec->{in};
146 my $name = $parameter_spec->{name};
147 my $required = $parameter_spec->{required};
148  
149 if ( $in eq 'body' ) { # complex data structure in HTTP body
150 my $input = $request->data;
151 my $schema = $parameter_spec->{schema};
152  
153 push @errors, _validator()->validate_input( $input, $schema );
154 }
155 else { # simple key-value-pair in HTTP header/query/path/form
156 my $type = $parameter_spec->{type};
157 my @values;
158  
159 if ( $in eq 'header' ) {
160 @values = $request->header($name);
161 }
162 elsif ( $in eq 'query' ) {
163 @values = $request->query_parameters->get_all($name);
164 }
165 elsif ( $in eq 'path' ) {
166 @values = $request->route_parameters->get_all($name);
167 }
168 elsif ( $in eq 'formData' ) {
169 @values = $request->body_parameters->get_all($name);
170 }
171 else { die "Unknown value for property 'in' of parameter '$name'" }
172  
173 # TODO align error messages to output style of SchemaValidator
174 if ( @values == 0 and $required ) {
175 $required and push @errors, "No value for parameter '$name'";
176 next;
177 }
178 elsif ( @values > 1 ) {
179 push @errors, "Multiple values for parameter '$name'";
180 next;
181 }
182  
183  
184 my $value = $values[0];
185  
186 # TODO steal more from Mojolicious::Plugin::Swagger2 ;-)
187 if ($type and defined ($value //= $parameter_spec->{default})) {
188 if (($type eq 'integer' or $type eq 'number') and $value =~ /^-?\d/) {
189 $value += 0;
190 }
191 elsif ($type eq 'boolean') {
192 $value = (!$value or $value eq 'false') ? '' : 1;
193 }
194 }
195  
196 my %input = defined $value ? ( $name => $value ) : ();
197 my %schema = ( properties => { $name => $parameter_spec } );
198  
199 $required and $schema{required} = [$name];
200  
201 push @errors, _validator()->validate_input( \%input, \%schema );
202 }
203 }
204  
205 return @errors;
206 }
207  
208 sub _validate_response {
209 my ( $method_spec, $response, $result ) = @_;
210  
211 my $responses = $method_spec->{responses};
212 my $status = $response->status;
213  
214 my @errors;
215  
216 if ( my $response_spec = $responses->{$status} || $responses->{default} ) {
217  
218 my $headers = $response_spec->{headers};
219  
220 while ( my ( $name => $header_spec ) = each %$headers ) {
221 my @values = $response->header($name);
222  
223 if ( $header_spec->{type} eq 'array' ) {
224 push @errors,
225 _validator()->validate_input( \@values, $header_spec );
226 }
227 else {
228 if ( @values == 0 ) {
229 next; # you can't make a header 'required' in Swagger2
230 }
231 elsif ( @values > 1 ) {
232  
233 # TODO align error message to output style of SchemaValidator
234 push @errors, "header '$name' has multiple values";
235 next;
236 }
237  
238 push @errors,
239 _validator()->validate_input( $values[0], $header_spec );
240 }
241 }
242  
243 if ( my $schema = $response_spec->{schema} ) {
244 push @errors, _validator()->validate_input( $result, $schema );
245 }
246 }
247 else {
248 # TODO Call validate_input($response, {}) like
249 # in Mojolicious::Plugin::Swagger2?
250 # Swagger2-0.71/lib/Mojolicious/Plugin/Swagger2.pm line L315
251 }
252  
253 return @errors;
254 }
255  
256  
257 sub _default_controller_factory {
258 # TODO simplify argument list
259 my ( $method_spec, $http_method, $path, $dsl, $conf, $args, ) = @_;
260  
261 # from Dancer2 app
262 my $namespace = $args->{controller} || $conf->{controller};
263 my $app = $dsl->app->name;
264  
265 # from Swagger2 file
266 my $module;
267 my $method = $method_spec->{operationId};
268 if ( $method =~ s/^(.+)::// ) { # looks like Perl module
269 $module = $1;
270 }
271  
272 # different candidates possibly reflecting operationId
273 my @controller_candidates = do {
274 if ($namespace) {
275 if ($module) { $namespace . '::' . $module, $module }
276 else { $namespace }
277 }
278 else {
279 if ($module) {
280 ( # parens for better layout by Perl::Tidy
281 $app . '::' . $module,
282 $app . '::Controller::' . $module,
283 $module, # maybe a top level module name?
284 );
285 }
286 else { $app, $app . '::Controller' }
287 }
288 };
289  
290 # check candidates
291 for my $controller (@controller_candidates) {
292 local $@;
293 if ( ! eval { use_module( $controller ); 1; } ) {
294 if ( $@ && $@ =~ m/^Can't locate / ) { # module doesn't exist
295 DEBUG and warn "Can't load '$controller'";
296  
297 # don't do `next` here because controller could be
298 # defined in other package ...
299 }
300 else { # module doesn't compile
301 die $@;
302 }
303 }
304  
305 if ( my $cb = $controller->can($method) ) {
306 return $cb; # confirmed candidate
307 }
308 else {
309 DEBUG and warn "Controller '$controller' can't '$method'";
310 }
311 }
312  
313 # none found
314 warn "Can't find any handler for operationId '$method_spec->{operationId}'";
315 return;
316 }
317  
318 my $validator;
319 sub _validator { $validator ||= Swagger2::SchemaValidator->new }
320  
321  
322 1;
323  
324 __END__
↑ Summary