1 package Koha::REST::Plugin::PluginRoutes;
3 # This file is part of Koha.
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20 use Mojo::Base 'Mojolicious::Plugin';
22 use Koha::Exceptions::Plugin;
25 use Clone qw( clone );
26 use JSON::Validator::Schema::OpenAPIv2;
27 use Try::Tiny qw( catch try );
31 Koha::REST::Plugin::PluginRoutes
42 my ( $self, $app, $config ) = @_;
44 my $spec = $config->{spec};
45 my $validate = $config->{validate};
49 if ( C4::Context->config("enable_plugins") )
51 # plugin needs to define a namespace
52 @plugins = Koha::Plugins->new()->GetPlugins(
54 method => 'api_namespace',
58 foreach my $plugin ( @plugins ) {
59 $spec = $self->inject_routes( $spec, $plugin, $validate, $app->log );
72 my ( $self, $spec, $plugin, $validate, $logger ) = @_;
74 return merge_spec( $spec, $plugin ) unless $validate;
78 my $backup_spec = merge_spec( clone($spec), $plugin );
79 if ( $self->spec_ok( $backup_spec ) ) {
80 $spec = merge_spec( $spec, $plugin );
83 Koha::Exceptions::Plugin->throw(
84 "The resulting spec is invalid. Skipping " . $plugin->get_metadata->{name}
92 my $class = ref $plugin;
93 $logger->error( "Plugin $class route injection failed: $error" );
103 my ( $spec, $plugin ) = @_;
105 if($plugin->can('api_routes')) {
106 my $plugin_spec = $plugin->api_routes;
108 foreach my $route ( keys %{ $plugin_spec } ) {
109 my $THE_route = '/contrib/' . $plugin->api_namespace . $route;
110 if ( exists $spec->{ $THE_route } ) {
111 # Route exists, overwriting is forbidden
112 Koha::Exceptions::Plugin::ForbiddenAction->throw(
113 "Attempted to overwrite $THE_route"
117 $spec->{'paths'}->{ $THE_route } = $plugin_spec->{ $route };
121 if($plugin->can('static_routes')) {
122 my $plugin_spec = $plugin->static_routes;
124 foreach my $route ( keys %{ $plugin_spec } ) {
126 my $THE_route = '/contrib/' . $plugin->api_namespace . '/static'.$route;
127 if ( exists $spec->{ $THE_route } ) {
128 # Route exists, overwriting is forbidden
129 Koha::Exceptions::Plugin::ForbiddenAction->throw(
130 "Attempted to overwrite $THE_route"
134 $spec->{'paths'}->{ $THE_route } = $plugin_spec->{ $route };
145 my ( $self, $spec ) = @_;
147 my $schema = JSON::Validator::Schema::OpenAPIv2->new( $spec );
149 if ($schema->is_invalid) {
150 warn $schema->errors->[0];
153 return !$schema->is_invalid;