Search code examples
perlmojolicious

Roles and monkeypatching Mojo::Message::Response


I am trying to add a role to Mojo::UserAgent that handles queries to the wikidata SPARQL service.

In particular, I'd like to be able to munge the response so that the JSON that is delivered by the service is more usable.

The gist of it is that I'd like to be able to write

my $ua = Mojo::UserAgent->new->with_roles('+Wikidata');

my $tx = $ua->query($some_sparql); # ->query is defined by Mojo::UserAgent::Role::Wikidata

my $items = $tx->res->items; # this is the crux of the question

but this would mean - as far as I can tell:

  • catching transactions generated by a user agent with a Wikidata role
  • monkey-patch or add a role to the responses in those transactions

The questions are:

  1. is that a bad idea?
  2. if no, how do I do that?

Solution

  • I'd just create a wrapper:

    sub query {
        ... do whatever you need to make the request from the query ...
        my $tx = $ua->get( ... );
        ... do whatever you want to extract results ...
        }
    

    I'd rather leave the user-agent level and the application level separate. Since your added functionally has nothing to do with being a user-agent, I don't think you should add it the user-agent object.