rakucro

How to share a variable between two routers module in cro?


I try to use Cro to create a Rest API that will publish messages in rabbitMQ. I would like to split my routes in different modules and compose them with an "include". But I would like to be able to share the same connection to rabbitMQ in each of those modules too. I try with "our" but it does not work :

File 1:

unit module XXX::YYY;
use Cro::HTTP::Router;
use Cro::HTTP::Server;
use Cro::HTTP::Log::File;
use XXX::YYY::Route1;

use Net::AMQP;

our $rabbitConnection is export = Net::AMQP.new;
await $rabbitConnection.connect;

my $application = route {
        include <api v1 run> => run-routes;
}
...

File 2:

unit module XXX::YYY::Route1;
use UUID;
use Cro::HTTP::Router;
use JSON::Fast;
use Net::AMQP;
my $channel = $XXX::YYY::rabbitConnection.open-channel().result;
$channel.declare-queue("test_task", durable=> True );
sub run-routes() is export { ... }

Error message:

===SORRY!===
No such method 'open-channel' for invocant of type 'Any'

Thanks!


Solution

  • When you define your exportable route function you can specify arguments then in your composing module you can create the shared objects and pass them to the routes. For example in your router module :

    sub run-routes ($rmq) is export{
        route {
           ... $rmq is available in here
        }
    }
    

    Then in your main router you can create your Queue and pass it in when including

    my $rmq = # Insert queue creation code here
    include product => run-routes( $rmq );
    

    I've not tried this but I can't see any reason why it shouldn't work.