|
| 1 | +package com.baeldung.validations.functional.handlers; |
| 2 | + |
| 3 | +import org.springframework.http.HttpStatus; |
| 4 | +import org.springframework.validation.BeanPropertyBindingResult; |
| 5 | +import org.springframework.validation.Errors; |
| 6 | +import org.springframework.validation.Validator; |
| 7 | +import org.springframework.web.reactive.function.server.ServerRequest; |
| 8 | +import org.springframework.web.reactive.function.server.ServerResponse; |
| 9 | +import org.springframework.web.server.ResponseStatusException; |
| 10 | + |
| 11 | +import reactor.core.publisher.Mono; |
| 12 | + |
| 13 | +public abstract class AbstractValidationHandler<T, U extends Validator> { |
| 14 | + |
| 15 | + private final Class<T> validationClass; |
| 16 | + |
| 17 | + private final U validator; |
| 18 | + |
| 19 | + protected AbstractValidationHandler(Class<T> clazz, U validator) { |
| 20 | + this.validationClass = clazz; |
| 21 | + this.validator = validator; |
| 22 | + } |
| 23 | + |
| 24 | + abstract protected Mono<ServerResponse> processBody(T validBody, final ServerRequest originalRequest); |
| 25 | + |
| 26 | + public final Mono<ServerResponse> handleRequest(final ServerRequest request) { |
| 27 | + return request.bodyToMono(this.validationClass) |
| 28 | + .flatMap(body -> { |
| 29 | + Errors errors = new BeanPropertyBindingResult(body, this.validationClass.getName()); |
| 30 | + this.validator.validate(body, errors); |
| 31 | + |
| 32 | + if (errors == null || errors.getAllErrors() |
| 33 | + .isEmpty()) { |
| 34 | + return processBody(body, request); |
| 35 | + } else { |
| 36 | + return onValidationErrors(errors, body, request); |
| 37 | + } |
| 38 | + }); |
| 39 | + } |
| 40 | + |
| 41 | + protected Mono<ServerResponse> onValidationErrors(Errors errors, T invalidBody, final ServerRequest request) { |
| 42 | + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, errors.getAllErrors() |
| 43 | + .toString()); |
| 44 | + } |
| 45 | +} |
0 commit comments