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?