Reputation: 43
I'm trying to validate the request body then based on it either return a bad request or proceed further. The issue is that the proceed flow is not executed. I'm attaching two solutions that I have tried:
Solution 1
public Mono<ServerResponse> startOrder(ServerRequest request) {
return request.bodyToMono(OrderDto.class)
.map(order -> Utils.validate(order))
.flatMap(listErrors -> {
if(listErrors.isEmpty()){
Mono<OrderResponse> orderResponseMono = this.service.startOrder(request.bodyToMono(OrderDto.class));
return ServerResponse.ok().body(orderResponseMono, OrderResponse.class);
}
Mono<OrderResponse> res = Mono.just(new OrderResponse(HttpStatus.BAD_REQUEST.value(), new ApiError(list.toString())));
return ServerResponse.badRequest().body(res, OrderResponse.class);
});
}
Solution 2
return request.bodyToMono(OrderDto.class)
.map(tt -> Utils.validate(tt))
.filter(res -> !res.isEmpty())
.map(r -> new OrderResponse(HttpStatus.BAD_REQUEST.value(), new ApiError("validation errors")))
.switchIfEmpty(this.service.initOrder(request.bodyToMono(OrderDto.class), HeaderValues.create(request.headers())))
.flatMap(res -> ServerResponse.badRequest().body(Mono.just(res), OrderResponse.class));
Validation method
public static List<String> validate(OrderDto request) {
List<String> result = new ArrayList<>();
if(request.getId == null){
result.add("Id should not be null");
}
if(request.getTitle() == null){
result.add("Title should not be null");
}
if(request.getDescription() == null){
result.add("Description should not be null");
}
return result;
}
When validation succeeds, the body with the result is returned but not when it fails.
What can cause the Mono to not be executed?
Upvotes: 0
Views: 327
Reputation: 14732
The issue you have is that you are trying to consume the response twice by calling response.bodyToMono(OrderDTO.class)
two times in your code.
Once you have consumed the body from a response, the server will be able to close the connection to the called system.
If you call it multiple times it will (probably, not checked or verified) return a Mono.empty()
which means it will not continue the flow as expected.
You should make it a habit of consuming the response body as quick as possible so that the server can close the connection to free up resources instead of passing around the response object.
Since we are working with streams, the connection will not be freed until the response is consumed.
Upvotes: 3