Reputation: 27018
I have a spring webflux project. I have a controller method like this
@PostMapping("url")
public Mono<MyResponse> getMyResponse(@RequestBody Mono<MyRequest> myRequestMono) {
return urlService.getUrl(myRequestMono)
.doOnNext(url -> {
System.out.println("Generated URL: Successfully ");
})
.map(dto -> MyResponse.builder().url(dto).build())
.doOnError(e -> System.out.println("Error " + e));
}
My service class looks like this
public Mono<String> getUrl(Mono<MyRequest> myRequestMono) {
return myRequestMono.map(myRequest -> {
callSomething();
return "something";
});
}
What I want to do is, when I log the line "Generated URL: Successfully", I would like to log a field in MyRequest object coming in through the request.
How can I access that in .doOnNext
I saw that I can set this value in a context and access it using transformDeferredContextual
.
I tried it by implementing WebFilter
and adding it there, but cannot really access it in the controller
urlService.getUrl(myRequestMono)
.transformDeferredContextual((stringMono, contextView) ->
stringMono
.doOnNext(url -> {
contextView.get("key") // cannot get the object from this.
System.out.println("Generated URL: Successfully ");
})
.map(dto -> MyResponse.builder().url(dto).build())
.doOnError(e -> System.out.println("Error occurred " + e)));
is this the right approach? If not how do I tackle this issue. I need to access the original request that I received in the Http request in my .doOnNext
method. I can set this in my response object in service class and access it, but that is a bit hacky.
Upvotes: 0
Views: 1123
Reputation: 4201
@RequestBody Mono<MyRequest> myRequestMono
Actually in your case there is no need to use Mono
as @RequestBody
in controller, you can replace it with your object explicitly, there will be no blocking. And for further processing just wrap it with Mono.just()
So you can use your literal object in operators in your chain without worrying about blocking
According to WebFlux documentation:
The request body can be one of the following way and it will be decoded automatically in both the annotation and the functional programming models:
Account account
— the account is deserialized without blocking before the controller is invoked.
Mono<Account> account
— the controller can use the Mono to declare logic to be executed after the account is deserialized.
Flux<Account> accounts
— input streaming scenario.
Upvotes: 1