jhthorsen / openapi-client

A client for talking to an Open API powered server
11 stars 17 forks source link

Mixing in roles to generated classes #35

Closed rabbiveesh closed 2 years ago

rabbiveesh commented 2 years ago

The Problem

I've been setting up API clients for amazon's advertising APIs, and in the course of doing so, it was most convenient to mix in certain shared behaviors with a role.

The issue that I'm having is that I can't mix in roles nicely to the generated classes. For example:

OpenAPI::Client->with_roles('My::Awesome::Role')->new('path/to/spec.yaml')

Will still return a subclass of OpenAPI::Client, rather than a subclass of the package created by mixing in my role.

The alternative of

OpenAPI::Client->new('path/to/spec.yaml')->with_roles('My::Awesome::Role')

works, except that the behavior is surprising, b/c the role never gets instantiated, so the defaults for fields in the role are not set.

For reference, I use Moo::Role to create attributes (access to redis for storing access tokens, for example).

Ideas

Either the constructor for OpenAPI::Client should use a dynamic classname when generating the child class on lines 71-74, or there should be an extra argument for putting more stuff into the generated class. Or perhaps give access to the generated class before instantiating it?

Thanks for this wonderful module!

jhthorsen commented 2 years ago

Thanks for the feedback!

I'm sorry, but I don't see any issue with doing "with_roles" after the class has been generated. The documentation states that a new class is generated when calling new: https://github.com/jhthorsen/openapi-client/blob/a8025f9ba6e470366da2e931b08ceba7c3b3ffc4/lib/OpenAPI/Client.pm#L393-L395

I don't mind a PR though, as long as it's not too complex.