From b09e20f5d8b305e0597925dbe59f22cce7e19815 Mon Sep 17 00:00:00 2001 From: Martin Renvoize Date: Fri, 20 Dec 2024 13:18:40 +0000 Subject: [PATCH] Bug 38745: Add RPC Router This patch add an RPC controller under the REST API to act as a router for JSON-RPC 2.0 syle requests. --- Koha/REST/V1/RPC.pm | 64 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Koha/REST/V1/RPC.pm diff --git a/Koha/REST/V1/RPC.pm b/Koha/REST/V1/RPC.pm new file mode 100644 index 00000000000..cb8fe8fbad5 --- /dev/null +++ b/Koha/REST/V1/RPC.pm @@ -0,0 +1,64 @@ +package Koha::REST::V1::RPC; + +# Copyright PTFS Europe 2024 +# +# This file is part of Koha. +# +# Koha is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# Koha is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Koha; if not, see . + +use Modern::Perl; + +use Mojo::Base 'Mojolicious::Controller'; + +=head1 API + +=head2 Methods + +=head3 process + +=cut + +sub process { + my $c = shift->openapi->valid_input or return; + + # Parse incoming JSON-RPC payload + my $payload = $c->req->json; + + my $method = $payload->{method}; + my $params = $payload->{params}; + my $id = $payload->{id}; + + # Route to handlers + if ($method =~ /^([\w\.]+):([\w]+)$/) { + my ($class_path, $action) = ($1, $2); + + # Map JSON-RPC class path to Perl module + my $module = "Koha::REST::V1::" . join('::', map { ucfirst } split(/\./, $class_path)); + + if ( $module->can($action) ) { + my $result = eval { $module->$action( $c, $params ) }; + if ($@) { + $c->app->log->error("Error in $method: $@"); + return $c->render( + json => { jsonrpc => '2.0', error => { code => -32603, message => 'Internal Error' }, id => $id } ); + } + return $c->render( json => { jsonrpc => '2.0', result => $result, id => $id } ); + } + } + + return $c->render( + json => { jsonrpc => '2.0', error => { code => -32601, message => 'Method not found' }, id => $id } ); +} + +1; -- 2.47.1