| 1 | package APISchema::Generator::Router::Simple; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | |||
| 5 | use Hash::Merge::Simple qw(merge); | ||
| 6 | use Class::Load qw(load_class); | ||
| 7 | use Class::Accessor::Lite ( | ||
| 8 | new => 1, | ||
| 9 | ro => [qw(router_class)], | ||
| 10 | ); | ||
| 11 | |||
| 12 | use constant ROUTER_CLASS => 'Router::Simple'; | ||
| 13 | |||
| 14 | sub generate_router { | ||
| 15 | my ($self, $schema) = @_; | ||
| 16 | |||
| 17 | my $router_class = $self->router_class // ROUTER_CLASS; | ||
| 18 | my $router = load_class($router_class)->new; | ||
| 19 | |||
| 20 | $self->inject_routes($schema, $router); | ||
| 21 | } | ||
| 22 | |||
| 23 | sub inject_routes { | ||
| 24 | my ($self, $schema, $router) = @_; | ||
| 25 | |||
| 26 | my $router_class = ref $router; | ||
| 27 | |||
| 28 | for my $route (@{$schema->get_routes}) { | ||
| 29 | my $option = $route->option // {}; | ||
| 30 | $option = merge $option, $option->{$router_class} // {}; | ||
| 31 | $router->connect($route->title, $route->route => $route->destination, { | ||
| 32 | method => $route->method, | ||
| 33 | map { $_ => $option->{$_} } qw(host on_match), | ||
| 34 | }); | ||
| 35 | } | ||
| 36 | |||
| 37 | $router; | ||
| 38 | } | ||
| 39 | |||
| 40 | 1; |