I'm using a RouterFunction
to define endpoints in my Spring Boot application. My service returns a Mono<Object>
and I want to return the result of this when the endpoint is called. I also need to authenticate so I pass a UserPrinciple
object through.
Router
@Bean
RouterFunction<ServerResponse> router() {
return route()
.GET("/api/endpoint-name", this::getExample)
.build();
}
private Mono<ServerResponse> getExample(ServerRequest request) {
return ServerResponse.ok().body(fromPublisher(getUserPrincipal().map(service::getSomething), Object.class)).log();
}
private Mono<UserPrincipal> getUserPrincipal() {
return ReactiveSecurityContextHolder.getContext()
.map(ctx -> ctx.getAuthentication())
.map(auth -> auth.getPrincipal())
.map(UserPrincipal.class::cast);
}
Service
public Mono<Object> getSomething(UserPrincipal userPrincipal) {
WebClient webClient = getWebClient(userPrincipal.getJwt());
return webClient.get()
.uri(uriBuilder -> uriBuilder.path("another/server/endpoint").build())
.retrieve()
.bodyToMono(Object.class);
}
The endpoint is returning this:
{
"scanAvailable": true
}
which suggests that I'm passing the Mono
into the body of the response instead of passing in the result. However I've used fromPublisher
which I thought would resolve this.
I can't find any examples where the service returns a Mono
and the route correctly returns the result of the Mono
.
How can I correctly pass a Mono/Flux
as the body of the response?