How to validate a model model in web flux SpringBoot

Viewed 21

I'm trying to move from traditional approach to Reactive style. Early days for me. One of the challenge I came into and could not make much progress is on model validation. With RestControllers, it was as easy as @Valid. I don't see anything out there to make it happen for Webflux way of doing things

package com.reactive.sbhello.handler;

import com.reactive.sbhello.model.Order;
import com.reactive.sbhello.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import javax.validation.Validator;

@Component
public class OrderHandler {
    @Autowired
    private OrderService orderService;
    private final Validator validator;

    public OrderHandler(Validator validator) {
        this.validator = validator;
    }

    public Mono<ServerResponse> getAll(ServerRequest request) {
        return ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(orderService.getAllOrders(),
                        Order.class
                );
    }

    public Mono<ServerResponse> getOrderInfo(ServerRequest request) {
        var orderId = request.pathVariable("orderId");
        var response = orderService.getOrderById(Integer.parseInt(orderId));
        return response.collectList()
                .flatMap(orders -> {
                    if(orders.isEmpty()) {
                        return ServerResponse.badRequest().body(BodyInserters.fromValue("Invalid OrderId"));
                    } else {
                        return ServerResponse.ok().body(BodyInserters.fromValue(orders));
                    }
                });
    }

    public  Mono<ServerResponse> addOrder(ServerRequest request) {
        return request.bodyToMono(Order.class)
                .flatMap(order -> orderService.addOrder(order))
                .flatMap(order -> ServerResponse.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue(order)));
    }
}

"addOrder" function at the moment lacks any validation. As a result, null values go through. Is there anyway to validate apart from doing it in service and bubble up the error? Or should I stick to RestController approach and still use streaming from there.

0 Answers
Related