| 1 | package Dancer2::Plugin::OpenAPIRoutes; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | # ABSTRACT: A Dancer2 plugin for creating routes from a Swagger2 spec | ||
| 7 | our $VERSION = '0.01'; # VERSION | ||
| 8 | use File::Spec; | ||
| 9 | use Dancer2::Plugin; | ||
| 10 | use Module::Load; | ||
| 11 | use Carp; | ||
| 12 | use JSON (); | ||
| 13 | use JSON::Pointer; | ||
| 14 | use YAML::XS; | ||
| 15 | use Data::Walk; | ||
| 16 | |||
| 17 | sub _path2mod { | ||
| 18 | ## no critic (BuiltinFunctions::ProhibitComplexMappings) | ||
| 19 | map {s/[\W_]([[:lower:]])/\u$1/g; ucfirst} @_; | ||
| 20 | } | ||
| 21 | |||
| 22 | sub _build_path_map { | ||
| 23 | my $schema = $_[0]; | ||
| 24 | my $paths = $schema->{paths}; | ||
| 25 | #<<< | ||
| 26 | my @paths = map { | ||
| 27 | my $p = $_; | ||
| 28 | my $ps = $_; | ||
| 29 | $p =~ s!/\{[^{}]+\}!!g; | ||
| 30 | my @m = grep {!/^x-/} keys %{$paths->{$_}}; | ||
| 31 | ($p, [map {+{method => $_, pspec => $ps}} @m]) | ||
| 32 | } | ||
| 33 | sort { ## no critic (BuiltinFunctions::RequireSimpleSortBlock) | ||
| 34 | my @a = split m{/}, $a; | ||
| 35 | my @b = split m{/}, $b; | ||
| 36 | @b <=> @a; | ||
| 37 | } | ||
| 38 | grep { | ||
| 39 | !/^x-/ && 'HASH' eq ref $paths->{$_} | ||
| 40 | } | ||
| 41 | keys %{$paths}; | ||
| 42 | #>>> | ||
| 43 | my %paths; | ||
| 44 | ## no critic (ControlStructures::ProhibitCStyleForLoops) | ||
| 45 | for (my $i = 0; $i < @paths; $i += 2) { | ||
| 46 | my $p = $paths[$i]; | ||
| 47 | my $ma = $paths[$i + 1]; | ||
| 48 | my $m; | ||
| 49 | my $mn = @$ma; | ||
| 50 | if ($mn == 1 && !exists $paths{$p}) { | ||
| 51 | my @p = split m{/}, $p; | ||
| 52 | if (@p > 2) { | ||
| 53 | $m = pop @p; | ||
| 54 | } | ||
| 55 | $p = join "/", @p; | ||
| 56 | } | ||
| 57 | if ($m) { | ||
| 58 | push @{$paths{$p}}, $m; | ||
| 59 | my $ps = $ma->[0]{pspec}; | ||
| 60 | my $method = $ma->[0]{method}; | ||
| 61 | $paths->{$ps}{$method}{'x-path-map'} = { | ||
| 62 | module_path => $p, | ||
| 63 | func => $m | ||
| 64 | }; | ||
| 65 | } else { | ||
| 66 | for (@$ma) { | ||
| 67 | my $ps = $_->{pspec}; | ||
| 68 | my $method = $_->{method}; | ||
| 69 | push @{$paths{$p}}, $method; | ||
| 70 | $paths->{$ps}{$method}{'x-path-map'} = { | ||
| 71 | module_path => $p, | ||
| 72 | func => $method | ||
| 73 | }; | ||
| 74 | |||
| 75 | } | ||
| 76 | } | ||
| 77 | } | ||
| 78 | return \%paths; | ||
| 79 | } | ||
| 80 | |||
| 81 | my %http_methods_func_map = ( | ||
| 82 | get => 'fetch', | ||
| 83 | post => 'create', | ||
| 84 | patch => 'update', | ||
| 85 | put => 'replace', | ||
| 86 | delete => 'remove', | ||
| 87 | options => 'choices', | ||
| 88 | head => 'check' | ||
| 89 | ); | ||
| 90 | |||
| 91 | sub _path_to_fqfn { | ||
| 92 | my ($config, $schema, $path_spec, $method) = @_; | ||
| 93 | my $paths = $schema->{paths}; | ||
| 94 | my $module_name; | ||
| 95 | my $func = $paths->{$path_spec}{$method}{'x-path-map'}{func}; | ||
| 96 | my @pwsr = split m{/}, $paths->{$path_spec}{$method}{'x-path-map'}{module_path}; | ||
| 97 | $module_name = join "::", map {_path2mod $_ } @pwsr; | ||
| 98 | if ($module_name eq '') { | ||
| 99 | $module_name = $config->{default_module} || $config->{appname}; | ||
| 100 | } else { | ||
| 101 | $module_name = $config->{namespace} . $module_name; | ||
| 102 | } | ||
| 103 | $func = $http_methods_func_map{$func} if $http_methods_func_map{$func}; | ||
| 104 | return ($module_name, $func); | ||
| 105 | } | ||
| 106 | |||
| 107 | sub load_schema { | ||
| 108 | my $config = shift; | ||
| 109 | croak "Need schema file" if not $config->{schema}; | ||
| 110 | my $schema; | ||
| 111 | my $file = File::Spec->catfile($config->{app}->location, $config->{schema}); | ||
| 112 | if ($config->{schema} =~ /\.json/i) { | ||
| 113 | require Path::Tiny; | ||
| 114 | $schema = JSON::from_json(path($file)->slurp_utf8); | ||
| 115 | } elsif ($config->{schema} =~ /\.yaml/i) { | ||
| 116 | $schema = YAML::XS::LoadFile $file; | ||
| 117 | } | ||
| 118 | if ($schema && 'HASH' eq ref $schema) { | ||
| 119 | walkdepth + { | ||
| 120 | wanted => sub { | ||
| 121 | if ( "HASH" eq ref $_ | ||
| 122 | && exists $_->{'$ref'} | ||
| 123 | && !ref $_->{'$ref'} | ||
| 124 | && keys %$_ == 1) | ||
| 125 | { | ||
| 126 | (my $r = $_->{'$ref'}) =~ s/^#//; | ||
| 127 | my $rp = JSON::Pointer->get($schema, $r); | ||
| 128 | if ('HASH' eq ref $rp) { | ||
| 129 | %$_ = %$rp; | ||
| 130 | } else { | ||
| 131 | croak "Can't load schema part: " . YAML::XS::Dump($_); | ||
| 132 | } | ||
| 133 | } | ||
| 134 | } | ||
| 135 | }, $schema; | ||
| 136 | } | ||
| 137 | return $schema; | ||
| 138 | } | ||
| 139 | |||
| 140 | sub _make_handler_params { | ||
| 141 | my ($mpath, $parameters) = @_; | ||
| 142 | my $param_eval = ''; | ||
| 143 | for my $parameter_spec (@$parameters) { | ||
| 144 | next if $parameter_spec =~ /^x-/; | ||
| 145 | my $in = $parameter_spec->{in}; | ||
| 146 | my $name = $parameter_spec->{name}; | ||
| 147 | my $required = $parameter_spec->{required}; | ||
| 148 | my $req_code = "push \@errors, \"required parameter '$name'" . " is absent\" if not exists \$input{\"$name\"};\n "; | ||
| 149 | my $src; | ||
| 150 | ## no critic (ControlStructures::ProhibitCascadingIfElse) | ||
| 151 | if ($in eq 'body') { | ||
| 152 | $req_code | ||
| 153 | = $required | ||
| 154 | ? "push \@errors, \"required parameter '$name'" . " is absent\" if not keys %{\$input{\"$name\"}};" | ||
| 155 | : ''; | ||
| 156 | #<<< | ||
| 157 | $param_eval .= | ||
| 158 | "{ my \$value;\n" | ||
| 159 | . " if (\$app->request->header(\"Content-Type\")\n" | ||
| 160 | . " && \$app->request->header(\"Content-Type\") =~ m{application/json}) {\n" | ||
| 161 | . " \$value = JSON::decode_json (\$app->request->body)\n } else {\n" | ||
| 162 | . " \$value = \$app->request->body }\n" | ||
| 163 | . " \$input{\"$name\"} = \$value if defined \$value; $req_code" | ||
| 164 | . "}\n"; | ||
| 165 | #>>> | ||
| 166 | $req_code = ''; | ||
| 167 | } elsif ($in eq 'header') { | ||
| 168 | $param_eval .= "\$input{\"$name\"} = \$app->request->header(\"$name\");\n"; | ||
| 169 | } elsif ($in eq 'query') { | ||
| 170 | $src = "\$app->request->params('query')"; | ||
| 171 | } elsif ($in eq 'path') { | ||
| 172 | if ($parameter_spec->{type} && $parameter_spec->{type} eq 'integer') { | ||
| 173 | $mpath =~ s/:$name\b/\\E(?<$name>\\d+)\\Q/; | ||
| 174 | $src = "\$app->request->captures"; | ||
| 175 | } else { | ||
| 176 | $src = "\$app->request->params('route')"; | ||
| 177 | } | ||
| 178 | } elsif ($in eq 'formData') { | ||
| 179 | if ($parameter_spec->{type} && $parameter_spec->{type} eq 'file') { | ||
| 180 | $param_eval .= "\$input{\"$name\"} = \$app->request->upload(\"$name\");\n"; | ||
| 181 | } else { | ||
| 182 | $src = "\$app->request->params('body')"; | ||
| 183 | } | ||
| 184 | } | ||
| 185 | if ($src) { | ||
| 186 | $param_eval .= "{ my \$src = $src; \$input{\"$name\"} = " . "\$src->{\"$name\"} if 'HASH' eq ref \$src; }\n"; | ||
| 187 | } | ||
| 188 | $param_eval .= $req_code if $required; | ||
| 189 | } | ||
| 190 | $param_eval .= "if(\@errors) { \$dsl->status('bad_request'); \$res = { errors => \\\@errors }; }\n"; | ||
| 191 | if ($mpath =~ /\(\?</) { | ||
| 192 | $mpath = "\\Q$mpath\\E"; | ||
| 193 | $mpath =~ s/\\Q(.*?)\\E/quotemeta($1)/eg; | ||
| 194 | $mpath = qr|$mpath|; | ||
| 195 | } | ||
| 196 | return ($mpath, $param_eval); | ||
| 197 | } | ||
| 198 | |||
| 199 | sub _path_compare { | ||
| 200 | my $ssc = sub { | ||
| 201 | length($_[1]) >= length($_[0]) | ||
| 202 | && substr($_[1], 0, 1 + length $_[0]) eq "$_[0]/"; | ||
| 203 | }; | ||
| 204 | return 0 if $a eq $b; | ||
| 205 | if ($ssc->($a, $b)) { | ||
| 206 | return 1; | ||
| 207 | } | ||
| 208 | if ($ssc->($b, $a)) { | ||
| 209 | return -1; | ||
| 210 | } | ||
| 211 | return $a cmp $b; | ||
| 212 | } | ||
| 213 | |||
| 214 | register OpenAPIRoutes => sub { | ||
| 215 | my ($dsl, $debug) = @_; | ||
| 216 | my $app = $dsl->app; | ||
| 217 | local $SIG{__DIE__} = sub {Carp::confess(@_)}; | ||
| 218 | my $config = plugin_setting; | ||
| 219 | $config->{app} = $app; | ||
| 220 | $config->{appname} = $dsl->config->{appname}; | ||
| 221 | my $schema = load_schema($config); | ||
| 222 | my $paths = $schema->{paths}; | ||
| 223 | _build_path_map($schema); | ||
| 224 | |||
| 225 | for my $path_spec (sort _path_compare keys %$paths) { | ||
| 226 | next if $path_spec =~ /^x-/; | ||
| 227 | my $path = $path_spec; | ||
| 228 | $path =~ s/\{([^{}]+?)\}/:$1/g; | ||
| 229 | for my $method (sort keys %{$paths->{$path_spec}}) { | ||
| 230 | next if $method =~ /^x-/; | ||
| 231 | my ($module_name, $module_func) = _path_to_fqfn($config, $schema, $path_spec, $method); | ||
| 232 | if ($module_func eq 'create' && $path =~ m{/:[^:/]+$}) { | ||
| 233 | $module_func = 'update'; # EXCEPTION RULE!!! | ||
| 234 | } | ||
| 235 | my @parameters; | ||
| 236 | if ($paths->{$path_spec}{$method}{parameters}) { | ||
| 237 | @parameters = @{$paths->{$path_spec}{$method}{parameters}}; | ||
| 238 | } | ||
| 239 | my ($mpath, $param_eval) = _make_handler_params($path, \@parameters); | ||
| 240 | my $dancer_method = $method eq 'delete' ? 'del' : $method; | ||
| 241 | my $get_env = ''; | ||
| 242 | for (grep {/^x-env-/} keys %{$paths->{$path_spec}{$method}}) { | ||
| 243 | my $name = $paths->{$path_spec}{$method}{$_}; | ||
| 244 | my ($env_var) = /^x-env-(.+)/; | ||
| 245 | $env_var = uc $env_var; | ||
| 246 | $env_var =~ s/\W/_/; | ||
| 247 | $get_env .= "\$input{'$name'} = \$app->request->env->{'$env_var'} // '';\n"; | ||
| 248 | } | ||
| 249 | my $prolog_code_src = <<"EOS"; | ||
| 250 | sub { | ||
| 251 | my %input = (); | ||
| 252 | my \@errors = (); | ||
| 253 | my \$res; | ||
| 254 | my \$status; | ||
| 255 | my \$callback; | ||
| 256 | $param_eval; | ||
| 257 | $get_env; | ||
| 258 | (\$res, \$status, \$callback) = eval {${module_name}::$module_func( \\%input, \$dsl )} if not \$res; | ||
| 259 | if(\$callback && 'CODE' eq ref \$callback) { | ||
| 260 | \$callback->(); | ||
| 261 | } | ||
| 262 | if( \$app->request->header(\"Accept\") | ||
| 263 | && \$app->request->header(\"Accept\") =~ m{application/json} | ||
| 264 | && (\$\@ || ref \$res)) { | ||
| 265 | \$dsl->content_type("application/json"); | ||
| 266 | if (not defined \$res) { | ||
| 267 | \$res = { error => \$\@ }; | ||
| 268 | \$res->{error} =~ s/ at .*? line \\d+\.\n?//; | ||
| 269 | \$dsl->status('bad_request'); | ||
| 270 | } else { | ||
| 271 | \$dsl->status(\$status) if \$status; | ||
| 272 | } | ||
| 273 | return JSON::encode_json \$res; | ||
| 274 | } else { | ||
| 275 | die \$\@ if \$\@ and not defined \$res; | ||
| 276 | \$dsl->status(\$status) if \$status; | ||
| 277 | return \$res; | ||
| 278 | } | ||
| 279 | } | ||
| 280 | EOS | ||
| 281 | ## no critic (BuiltinFunctions::ProhibitStringyEval) | ||
| 282 | my $prolog_code = eval $prolog_code_src; | ||
| 283 | my $route = Dancer2::Core::Route->new( | ||
| 284 | method => $method, | ||
| 285 | regexp => $mpath, | ||
| 286 | code => $prolog_code, | ||
| 287 | prefix => $app->prefix | ||
| 288 | ); | ||
| 289 | if ($app->route_exists($route)) { | ||
| 290 | croak "Route $method $mpath is already exists"; | ||
| 291 | } | ||
| 292 | $debug && $dsl->debug("$dancer_method $mpath -> $module_func in module $module_name\n"); | ||
| 293 | my $success_load = eval {load $module_name; 1}; | ||
| 294 | croak "Can't load module $module_name for path $path_spec: $@" | ||
| 295 | if not $success_load or $@; | ||
| 296 | my $cref = "$module_name"->can($module_func); | ||
| 297 | croak "Can't find function $module_func in module $module_name for path $path_spec" | ||
| 298 | if not $cref; | ||
| 299 | $dsl->$dancer_method($mpath => $prolog_code); | ||
| 300 | } | ||
| 301 | } | ||
| 302 | }; | ||
| 303 | |||
| 304 | register_plugin; | ||
| 305 | |||
| 306 | 1; | ||
| 307 | __END__ |