With the below implementation, the expectation is that, it would go to switchIfEmpty
if Mono<Optional<Item>>
is empty, but not working as expected.
public Mono<ServerResponse> getItemById(ServerRequest request) {
JwtClaim claim = retrieveClaimFromRequest(request);
String itemId = request.pathVariable("itemId");
Mono<ServerResponse> notFound = ServerResponse.notFound().build();
Mono<Optional<Item>> item = Mono.just(itemRepository.findById(Long.parseLong(itemId)));
return item
.flatMap(retItem -> ServerResponse.ok().contentType(APPLICATION_JSON).bodyValue(retItem))
.switchIfEmpty(notFound);
}
Mono<Optional<Object>>
? ThebodyValue
will be set to anOptional<Item>
, not toItem
. Also is there a specific reason you are usingflatMap
instead ofmap
? - Turing85Mono
belong? I guess Reactor? - Turing85Mono<Item> item = Mono.just(itemRepository.findById(Long.parseLong(itemId)).orElse(null));
could fix it, but is not null-safe. If you expect thefindById
to return something, you may want to throw an applicable exception by callingorElseThrow(...)
instead. - Turing85