1

I have a simple rest controller (using spring web-FLUX), that get a bean to save in database. But as usual, I would like to validate some fields of it before saving.

I have a validation method to be called before save the bean. But how could I do that in a more functional (and appropriate) manner?

I have tried something like:

public void save(Mono<MyBean> myBean) {
    myBean.map(this::validateBean).map(myRepository::save)
}

But the method validateBean is not being called, only when I do something like

public void save(Mono<MyBean> myBean) {
    myBean.map(this::validateBean)
          .map(myRepository::save)
          .subscribe();
}

I don't know if the subscribe part is the most correct one (I believe it isn't), but I think it works because is kind of a terminal operation. Am I right?

Even so, that does not solve my problem, because my validation method throws a BusinessException when something is wrong with the bean. And that is exactly what I wanna do.

[EDITED] This is my rest controller would me something like:

@PostMapping(value = "/something")
public Mono<ResponseEntity> salvar(@RequestBody MyBean myBean) {
    return myService.salvar(myBean)
            .map(RestResponses::ok)
            .defaultIfEmpty(RestResponses.empty());
}

I know this is not working because my service ir no returning anything. But I do not know what would be the correct way. So I just post an idea. Thanks for understanding...

Could you guys give me some help?

Igor Veloso
  • 487
  • 2
  • 8
  • 20
  • As far as I know Mono is a "cold" publisher, It means that it should have at least one subsciber to start emmiting data. – rvit34 Jun 03 '17 at 10:24
  • Could you show your actual controller method? Also, the core of this issue is probably the fact that you're relying on blocking methods returning void vs. a reactive repository that should return a `Mono` when saving the data. Note that subscribing yourself to a Publisher is usually a smell. – Brian Clozel Jun 03 '17 at 13:39
  • @rvit34, thanks for your comment. Could you please give me some reference about this, so I can understand it better? – Igor Veloso Jun 05 '17 at 13:03
  • @BrianClozel, Thanks for your comment. I edited my question. – Igor Veloso Jun 05 '17 at 13:08
  • see https://ordina-jworks.github.io/reactive/2016/12/12/Reactive-Programming-Spring-Reactor.html – rvit34 Jun 05 '17 at 14:54
  • your repository should be reactive as well, with a `Mono save(MyBean myBean)` signature – Brian Clozel Jun 06 '17 at 16:14
  • 1
    I also confused about validation when switch to webflux, see [here](https://stackoverflow.com/questions/48031647/what-is-the-best-way-to-validate-request-in-a-spring-webflux-functional-applicat) – Hantsy Jan 02 '18 at 03:43

0 Answers0