I am developing Spring Boot 2.7.0 and Reactive Microservices using Spring WebFlux.
Below is the code
public void placeOrder(OrderRequest orderRequest) {
List<OrderLineItems> orderLineItems = orderRequest.getOrderLineItemsDtoList()
.stream()
.map(this::mapToDto)
.collect(Collectors.toList());
Order order = new Order();
order.setOrderNumber(UUID.randomUUID().toString());
order.setOrderLineItemsList(orderLineItems);
List<String> skuCodes = order.getOrderLineItemsList()
.stream()
.map(orderLineItem -> orderLineItem.getSkuCode())
.collect(Collectors.toList());
// Call Inventory Service, and place order if product is in stock
InventoryResponse[] inventoryResponsArray = webClient.get()
.uri("http://localhost:8092/api/inventory",
uriBuilder -> uriBuilder.queryParam("skuCode", skuCodes).build())
.retrieve()
.bodyToMono(InventoryResponse[].class)
.block();
boolean allProductsInStock = Arrays.stream(inventoryResponsArray)
.allMatch(InventoryResponse::isInStock);
if(allProductsInStock){
orderRepository.save(order);
} else {
throw new IllegalArgumentException("Product is not in stock, please try again later");
}
}
Is there any way to combine below two codes into one?
// Call Inventory Service, and place order if product is in stock
InventoryResponse[] inventoryResponsArray = webClient.get()
.uri("http://localhost:8092/api/inventory",
uriBuilder -> uriBuilder.queryParam("skuCode", skuCodes).build())
.retrieve()
.bodyToMono(InventoryResponse[].class)
.block();
boolean allProductsInStock = Arrays.stream(inventoryResponsArray)
.allMatch(InventoryResponse::isInStock);
CodePudding user response:
I can think of the simplest solution would be below:
// Call Inventory Service, and place order if product is in stock
boolean allProductsInStock = webClient.get()
.uri("http://localhost:8092/api/inventory", uriBuilder -> uriBuilder.queryParam("skuCode", skuCodes).build())
.retrieve()
.bodyToMono(InventoryResponse[].class)
.map(e -> Arrays.stream(e))
.block()
.allMatch(InventoryResponse::isInStock);