Reputation: 1778
In my app I have a custom Auth
object that I set as a request parameter in a filter.
No problems there, but now all my conrollers look like
@Controller("/path")
public class MyController {
@Get
public Whatever get(HttpRequest<?> request) {
Auth auth = request.getAttribute(SomeClass.AUTH_ATTRIBUTE_NAME);
// code code code
}
@Post
public Whatever post(HttpRequest<?> request, @Body SomePojo body) {
Auth auth = request.getAttribute(SomeClass.AUTH_ATTRIBUTE_NAME);
// code code code
}
}
I would really like to somehow "teach" micronaut how to treat Auth
like HttpRequest
, HttpHeaders
and the other values at Table 1. Bindable Micronaut Interfaces in the docs.
Basically I'd like to turn the above in:
@Controller("/path")
public class MyController {
@Get
public Whatever get(Auth auth) {
// code code code
}
@Post
public Whatever post(Auth auth, @Body SomePojo body) {
// code code code
}
}
Is there a way to do so?
I'm on micronaut 1.2.7. I tried
@Singleton
class AuthTypeConverterRegistrar implements TypeConverterRegistrar {
@Override
public void register(ConversionService<?> conversionService) {
conversionService.addConverter(HttpRequest.class, Auth.class, request -> {
return request.getAttribute("").map(Auth.class::cast).orElse(Auth.anonymous());
});
}
}
but it doesn't seem to work as I hoped.
Upvotes: 1
Views: 1547
Reputation: 12238
You need to register a TypedRequestArgumentBinder
bean.
You can look at SessionArgumentBinder
as an example on how this is done because the session is just a request attribute as well.
Upvotes: 3